gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:31:38 25 4
gpt4 key购买 nike

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

最佳答案

您无法在 run block 内获取 ng-init 值

Angular 生命周期

  1. 配置阶段 (app.config)($rootScope 此处不可用)
  2. 运行阶段 (app.run)($rootScope 将在此处可用)
  3. 指令获取 Compile()
  4. 然后执行 Controller 、指令链接函数、过滤器等。(ng-init 在这里)

如果你想在运行阶段获取初始化值,那么你需要在配置阶段设置该值。

如果你想在配置中设置值,那么你可以使用配置阶段可用的app.constant/provider,不要使用 $rootScope 在 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);
})

关于AngularJS - 从 run 方法访问 ng-init 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29940852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com