3

1) I have variables initialized in ng-init Eg -

ng-init="password='Mightybear'";

2) I want to access it from the .run method. Eg -

anguar.module("ngApp", [])
.run(function() {
//Access password here
});

Below scenarios I have tried, and 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!!!
});
});

2 Answers 2

3

You can not get ng-init value inside your run block

Angular LifeCycle

  1. Config Phase (app.config) ($rootScope will not available here)
  2. Run Phase (app.run) ($rootScope will available here)
  3. Directive Gets Compile()
  4. Then controller, directive link function, filter, etc gets executed.(ng-init is here)

If you want to get initialize value in run phase then you need to set that value in config phase.

If You want to set the value in config then you can take use of app.constant/provider which available in configuration phase, don't use $rootScope that is considered as bad pattern in AngularJS.

Code

var app = angular.module('app', []);

app.constant('settings', {
    title: 'My Title'
})

app.config(function(settings) {
    setting.title = 'Changed My Title';
    //here can you do other configurarion setting like route & init some variable
})

app.run(function(settings) {
    console.log(settings.title);
})
Sign up to request clarification or add additional context in comments.

7 Comments

Is app.contant an alternative to global variables? or is it global variables for the angular app?
app.constant is not global variable thing..you can consider it as one sort of factory..which can contains a static data..
I need to use it from ng-init and .run only. any ideas? Can i add watch on rootscope?
why you don't use constant..tell me scenario what you want to do..I'll guide you
I am writing my ng-init in a jsp. I am dynamically getting username/password in jsp which i want to add in ng-init. And these needsd to be accessed from the .run method.
|
0

I'll let you a walkthrough, of how angular loads

angular module ---> .config ----> .run ----> controllers(ng-init)

now you can clear your approach.

1 Comment

Am new to Angular. My guess is to use $watch. $rootScope.$watch?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.