AngularJS $ rootScope变量存在,但无法访问 [英] AngularJS $rootScope variable exists, but not accessible
问题描述
我把在我的模块之一$ rootScope变量,现在要进入另一个模块相同$ rootScope变量。到目前为止,我可以看到,在变量已正确设置两个模块,但是当我尝试访问在$ rootScope变量,我只得到不确定的。
我如何可以访问此变量,而不做工厂/服务解决方法吗?变量是非常简单和$ rootScope应该能满足我的需要。我已经把一些通用的样品code以下来说明这个问题:
file1.js
VAR应用= angular.module('MyApp1',[]);app.controller(CTRL1',['$范围,$ rootScope',函数($范围,$ rootScope){
$ scope.myFunc =功能(){
$ rootScope.test = 1;
}
}
file2.js
VAR应用= angular.module('MyApp2',[]);app.controller('CTRL2',['$范围,$ rootScope',函数($范围,$ rootScope){
$ scope.need_to_access_this = $ rootScope.test; //未定义
的console.log($ rootScope); //返回JS对象W /测试属性设置为1
}
我只是停留在同样的问题,当我想通了,你有控制器或服务加载之前定义$ rootScope这些属性。因此,我所做的应用程序运行时设置inital值。在你的情况下,它会像:
app.run(函数($ rootScope){
$ rootScope.test =变量;
})
`
I set a $rootScope variable in one of my modules and now want to access that same $rootScope variable in another module. Thus far I can see that in both modules the variable has been set properly, but when I try accessing the variable in $rootScope, I only get undefined.
How can I access this variable without doing a factory/service workaround? The variable is really simple and $rootScope should suffice for what I need. I've put some generic sample code below to illustrate the issue:
file1.js
var app = angular.module('MyApp1', []);
app.controller('Ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.myFunc = function() {
$rootScope.test = 1;
}
}
file2.js
var app = angular.module('MyApp2', []);
app.controller('Ctrl2', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.need_to_access_this = $rootScope.test; // undefined
console.log($rootScope); // returns JS object w/ test property set to 1
}
I was just stuck in the same problem when I figured out that you have define those properties for $rootScope before the controllers or services load. So what I did was set inital values when the application runs. In your case it will be like:
app.run(function($rootScope){
$rootScope.test="variable";
})
`
这篇关于AngularJS $ rootScope变量存在,但无法访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!