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

AngularJS-从run方法访问ng init变量,angularjs,angularjs-ng-init,ng-init,angularjs-rootscope,angularjs-lifecycle,Angularjs,Angularjs Ng Init,Ng Init,Angularjs Rootscope,Angularjs Lifecycle,1) 我在ng init中初始化了变量 例如 2) 我想从.run方法访问它。 例如 anguar.module("ngApp", []) .run(function() { //Access password here }); 下面的场景我已经尝试过了,但没有成功- 1) angular.module("ngApp", []) .run(function($rootScope) { console.log($rootScope.password) //undefined!!! }); 2

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

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

我会给你一个演示,关于角载荷

角度模块-->.config-->.run-->控制器(ng init)


现在您可以清除您的方法

您无法在
run
块中获取ng init值

角度生命周期

  • 配置阶段(app.Config)($rootScope在此不可用)
  • 运行阶段(app.Run)(此处将提供$rootScope)
  • 指令get Compile()
  • 然后执行控制器、指令链接函数、过滤器等。(
    ng init
    在此)
  • 若您想在运行阶段获得初始化值,那个么需要在配置阶段设置该值

    如果您想在配置中设置值,那么可以使用配置阶段提供的
    app.constant
    /
    provider
    ,不要使用在AngularJS中被视为坏模式的
    $rootScope

    代码

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

    我是新来的。我猜是用$watch$rootScope.$watch?app.contant是全局变量的替代品吗?或者它是全局变量的角APP?App.常量不是全局变量的东西。你可以把它看作是一种工厂。它可以包含静态数据。我需要从NG init和.nit中使用它。有什么想法吗?我可以在rootscope上添加watch吗?为什么不使用constant..告诉我您想做什么..我会指导您我正在用jsp编写ng init。我在jsp中动态获取用户名/密码,我想将其添加到ng init中。这些需要从.run方法访问。
    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);
    })