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

  1. config phase (app.config) ($rootscope not available here)
  2. run phase (app.run) ($rootscope available here)
  3. directive gets compile()
  4. 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

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -