【发布时间】: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