AngularJS在设置时获取rootScope变量

时间:2016-12-28 20:28:21

标签: angularjs watch

在我正在开展的项目中,我们在名为$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变量调用。目前它返回一个空变量。如果我错了,请在评论中告诉我。

3 个答案:

答案 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)

RootScope documentation

监视字符串(范围变量)或函数。

$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.
});