AngularJS - 从run方法访问NG-初始化变量 [英] AngularJS - Accessing ng-init variables from run method

查看:1251
本文介绍了AngularJS - 从run方法访问NG-初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


  1. 配置阶段(的app.config)($ rootScope不会可在这里)

  2. 运行阶段(app.run)​​($ rootScope将可在这里)

  3. 指令获取编译()

  4. 然后控制器指令链接功能,过滤器等被执行。( 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-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!!!
});
});

解决方案

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

这篇关于AngularJS - 从run方法访问NG-初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆