AngularJS $rootScope 变量存在,但不可访问 [英] AngularJS $rootScope variable exists, but not accessible

查看:31
本文介绍了AngularJS $rootScope 变量存在,但不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一个模块中设置了一个 $rootScope 变量,现在想访问另一个模块中的同一个 $rootScope 变量.到目前为止,我可以看到在两个模块中都正确设置了变量,但是当我尝试访问 $rootScope 中的变量时,我只会得到未定义.

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.

如何在不执行工厂/服务解决方法的情况下访问此变量?该变量非常简单, $rootScope 应该足以满足我的需要.我在下面放置了一些通用示例代码来说明这个问题:

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
}

推荐答案

当我发现您已经在控制器或服务加载之前为 $rootScope 定义了这些属性时,我陷入了同样的问题.所以我所做的是在应用程序运行时设置初始值.在您的情况下,它将类似于:

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屋!

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