【问题标题】:AngualrJS Undefined or Null Reference When Accessing $rootSope in Controller在控制器中访问 $rootScope 时 AngularJS 未定义或空引用
【发布时间】:2013-09-13 21:49:02
【问题描述】:

AngularJS 最新候选版本:

我正在从模块的 run 函数中将一个名为 say stuff 的 javascript 对象放入 $rootScope 中,我认为它应该被阻止。这是代码:

'use strict';

/* App Module */

var app = angular.module('MyApp', ['ngRoute', 'API'])
    .run(function ($rootScope, API) {
        $rootScope.stuff = null;

        // call the API
        API.getStuff()
            .success(function(data){
                $rootScope.stuff = data;
            })
            .error(function(data){
                $rootScope.stuff = null;
            });

    });

现在,当我尝试从控制器访问 $rootScope 的 stuff 属性时,我在 stuff 上收到“未定义或空引用”错误。代码如下所示:

'use strict';

app.controller('indexController',
    function ($scope, $rootScope, otherAPI) {
        var
            stuff = $rootScope.stuff;

        // call the other API
        otherAPI.getDifferentStuff(stuff.property)
            .success(function(data){
                    $scope.differentStuff = data;
            })
            .error(function(data){
                        // do some error handling stuff here
            });
    });

我知道 run 函数中的 api 调用正在成功,它正在为 $rootScope 中的内容分配一个值。任何人都可以在这里看到我的代码有什么明显的问题吗?

感谢您的帮助!

丰富

【问题讨论】:

  • 为什么不直接在控制器中调用呢?将东西扔进根范围是不好的做法。如果您希望它可以在多个控制器中访问,请创建一个服务并将其注入每个控制器。
  • Zack,你能给我一个很好的例子,说明在 $rootScope 的使用方面被接受的做法吗?它似乎是放置所有控制器所需的全局信息的地方,因为它们的范围继承自 $rootScope。为什么要费心创建一个服务来作为一些数据项的容器呢?感谢您的帮助!

标签: javascript angularjs


【解决方案1】:

API.getStuff 是异步 api 调用吗(看起来很像)。在这种情况下,您的控制器很可能在异步调用返回之前被初始化,因此 $rootScope.stuff 仍然等于 null。如果您等到呼叫成功,那么您将获得您的数据。

【讨论】:

  • 谢谢,我相信你对正在发生的事情是正确的。显然,在包含的所有工作完成之前,运行功能不会阻塞。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 1970-01-01
  • 2017-02-18
  • 1970-01-01
  • 2017-05-14
相关资源
最近更新 更多