AngularJS - 从run方法访问ng-init变量

时间:2015-04-29 10:19:32

标签: angularjs angularjs-ng-init ng-init angularjs-rootscope angularjs-lifecycle

1)我在ng-init中初始化了变量 例如 -

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

2)我想从.run方法访问它。 例如 -

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

在我尝试过的场景中,并没有奏效 -

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 个答案:

答案 0 :(得分:3)

您无法在run

中获取ng-init值

Angular LifeCycle

  1. 配置阶段(app.config)(此处不提供$ rootScope)
  2. 运行阶段(app.run)($ rootScope将在此处提供)
  3. 指令获取编译()
  4. 然后执行控制器,指令链接功能,过滤器等。(ng-init在这里)
  5. 如果要在运行阶段获取初始化值,则需要在配置阶段设置该值。

    如果您想在配置中设置值,那么您可以使用配置阶段中可用的app.constant / provider,不要使用被认为是$rootScope的{​​{1}} AngularJS中的错误模式。

    <强>代码

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

答案 1 :(得分:0)

我会告诉你一个角度加载

的演练

角度模块---&gt; .config ----&gt; .run ----&gt;控制器(ng-init)

现在您可以清除您的方法。