AngularJS - Accessing ng-init variables from run method

浪尽此生 提交于 2019-12-14 03:49:35

问题


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!!!
});
});

回答1:


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);
})



回答2:


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

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

now you can clear your approach.



来源:https://stackoverflow.com/questions/29940852/angularjs-accessing-ng-init-variables-from-run-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!