问题描述
1)我在NG-INIT初始化的变量
EG -
NG-的init =密码='Mightybear';
2)我想从.RUN方法访问它。
EG -
anguar.module(ngApp,[])
.RUN(函数(){
这里//访问密码
});
下面的情景我都试过了,没有工作 -
1)angular.module(ngApp,[])
.RUN(函数($ rootScope){
的console.log($ rootScope.password)//未定义!
});2)angular.module(ngApp,[])
.RUN(函数($ rootScope,$超时){
$(超时(函数(){
的console.log($ rootScope.password)//未定义!
});
});
您无法将内得到NG-初始化值运行
块
角的LifeCycle
- 配置阶段(的app.config)($ rootScope不会可在这里)
- 运行阶段(app.run)($ rootScope将可在这里)
- 指令获取编译()
- 然后控制器指令链接功能,过滤器等被执行。(
NG-INIT
在这里)
如果你想获得初始化运行阶段值,那么你需要设置在配置阶段中的价值。
如果你想设置的配置价值,那么你可以使用 app.constant
/ 提供商
这在配置阶段可用,请不要使用 $ rootScope
被视为AngularJS错误的思路。
code
VAR应用= angular.module('应用',[]);app.constant(设置,{
标题:我的标题
})的app.config(功能(设置){
setting.title ='改变了我的标题;
//在这里你可以做其他configurarion设置类似的路线和放大器;初始化局部变量
})app.run(功能(设置){
的console.log(settings.title);
})
1) I have variables initialized in ng-initEg -
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!!!
});
});
You can not get ng-init value inside your run
block
Angular LifeCycle
- Config Phase (app.config) ($rootScope will not available here)
- Run Phase (app.run) ($rootScope will available here)
- Directive Gets Compile()
- 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);
})
这篇关于AngularJS - 从run方法访问NG-初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!