在我正在开展的项目中,我们在名为$rootScope
的{{1}}上获得了一个变量。在将控制器注入控制器之后,我可以使用events
在我的控制器中访问它。
服务在$rootScope.events
变量上设置事件可能需要一些时间。现在我要添加一个需要来自变量的第一个事件的ID的新功能。问题是,在$rootScope
设置之前调用它。在$rootScope.events
设置后,我无法弄清楚如何在控制器中调用该方法。我之前使用过$rootscope.events
,但它似乎并没有使用此变量。我试过的代码:
$watch
我添加了$scope.$watch('$rootScope.events', function() {
if ($rootScope.events.length > 0) {
getDetails(); // function I want to call after $rootscope.events is set
$log.debug($rootScope.events); // debugging line
}
});
以避免它进入无限循环。不确定是否有必要。我需要添加此功能的解决方案吗?像这样的手表吗?或者我做错了什么?
我认为您不需要更多代码,因为我只是在我的控制器中注入了$rootScope.events.length > 0
和$scope
,然后$rootScope
应该使用set变量调用。目前它返回一个空变量。如果我错了,请在评论中告诉我。
答案 0 :(得分:1)
已经有一段时间了,但我想你想要这个:
$rootScope.$watch('events', function() {
if ($rootScope.events.length > 0) {
getDetails(); // function I want to call after $rootscope.events is set
$log.debug($rootScope.events); // debugging line
}
});
events
是$rootscope
上的值,但$rootscope.events
不 $scope
上的值。
为避免手表混乱$rootscope
,您应该使用:
$scope.$watch('$root.events', function() {
var events = $scope.$root.events;
if (events.length > 0) {
getDetails(); // function I want to call after events is set
$log.debug(events); // debugging line
}
});
或者简单地说:
$scope.$watch('$root.events', function(newValue, oldValue) {
if (newValue.length > 0) {
getDetails(); // function I want to call after events is set
$log.debug(newValue); // debugging line
}
});
答案 1 :(得分:0)
监视字符串(范围变量)或函数。
$scope.$watch(function() {
return $rootScope.events;
}, function() {
console.log($rootScope.events);
}, true);
答案 2 :(得分:0)
您可以使用事件服务将在事件准备就绪时解决的承诺,而不是为一次发生的事情设置监视。
Event Service : ($rootScope & $q injected)
// in constructor :
this.deferred = $q.defer();
$rootScope.eventPromise = deferred.promise;
// in a setup fonction or even within the constructor
setupEvent : function(){
.. doing some stuff ..
.. somewhere in a asynchronous call back :
$rootScope.events =... //setup events
this.deferred.resolve();// or me.deferred using var me=this if some closure trouble
.. somewhere else if it fails ..
this.deferred.reject();
}
现在让我们确定这将在任何控制器加载之前运行:
angular.run(['EventService', function(EventService){
// if you do everything in the constructor let the angular.run and don't run any code,
// this will make sure your events will start loading before angular will resolve the current routes.
EventService.setupEvent();
}]);
现在让我们使用它:
$rootScope.eventPromise.then(function(){
$rootScope.events // we're safe here.
});