AngularJS - Accessing ng-init variables from run method -
1) have variables initialized in ng-init eg -
ng-init="password='mightybear'";
2) want access .run method. eg -
anguar.module("ngapp", []) .run(function() { //access password here });
below scenarios have tried, , did not work -
1) angular.module("ngapp", []) .run(function($rootscope) { console.log($rootscope.password) //undefined!!! }); 2) angular.module("ngapp", []) .run(function($rootscope, $timeout) { $(timeout(function() { console.log($rootscope.password) //undefined!!! }); });
you can not ng-init value inside run
block
angular lifecycle
- config phase (app.config) ($rootscope not available here)
- run phase (app.run) ($rootscope available here)
- directive gets compile()
- then controller, directive link function, filter, etc gets executed.(
ng-init
here)
if want initialize value in run phase need set value in config phase.
if want set value in config can take use of app.constant
/provider
available in configuration phase, don't use $rootscope
considered bad pattern in angularjs.
code
var app = angular.module('app', []); app.constant('settings', { title: 'my title' }) app.config(function(settings) { setting.title = 'changed title'; //here can other configurarion setting route & init variable }) app.run(function(settings) { console.log(settings.title); })
Comments
Post a Comment