AngularJS - Accessing ng-init variables from run method
1) I have variables initialized in ng-init For example -
ng-init="password='Mightybear'";
2) I want to access it from the .run method. For example -
anguar.module("ngApp", [])
.run(function() {
//Access password here
});
Below scripts I've tried and didn't 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!!!
});
});
+3
source to share
2 answers
You cannot get the ng-init value inside the block run
Angular LifeCycle
- Config Phase (app.config) ($ rootScope not available here)
- Run Phase (app.run) ($ rootScope will be available here)
- Directive gets compiled ()
- Then the controller, directive link function, filter, etc. are run. (
ng-init
here)
If you want to get the initialization value in the startup phase, you need to set this value in the configuration phase.
If you want to set a value in config, you can use app.constant
/ provider
which is available in the config phase, don't use $rootScope
which is considered a wrong template 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);
})
+3
source to share