什么时候触发angularjs` $ digest`?

时间:2017-01-03 04:28:41

标签: javascript angularjs angular-digest

我正在尝试实现一个检查用户是否不活动的函数。我的在线搜索建议我可以使用$rootScope.$watch来监控活动。但是,我对$digest触发器有点担心...因为我似乎无法确切地找到何时或哪个事件触发此事件。任何指针都将受到赞赏。

3 个答案:

答案 0 :(得分:1)

在我看来,单凭Angular的$ digest并不能解决这个问题。如果用户移动他们的鼠标,不应该重新启动空闲计时器?

我建议制作一个指令,在keydown和mousemove的$ window对象上创建一个事件监听器。然后创建一个服务,允许其他组件在用户的空闲状态发生变化时接收通知。

这样的事情:

angular
.module('myApp', [])
.service('Idle', function(){
  var self = {
		callbacks: {
			onidle: []
		},
		on: function(event, callback){
			event = 'on' + event.toLowerCase();
			if(self.callbacks[event] && typeof callback === 'function'){
				self.callbacks[event].push(callback);
			}
			return this;
		},
		trigger: function(event){
			event = 'on' + event.toLowerCase();
			if(self.callbacks[event])
			{
				lodash.each(self.callbacks[event], function(callback){
					callback.call();
				});
			}
			return this;
		}
  }
  
  return {
    on: self.on,
    trigger: self.trigger
  }
})
.directive('idleNotification',
function(
  $window,
  Idle
){
  return {
    link: function($scope){
      var timer = setTimer();

      angular
        .element($window)
        .on('keydown mousemove', function(){
          clearTimeout(timer);
          timer = setTimer();
        });
      
      function setTimer(){
        return setTimeout(function(){
          Idle.trigger('idle');
        }, 30);
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

然后像这样使用空闲服务:

Idle.on('idle', function(){
    // do something here when the user becomes idle
});

答案 1 :(得分:0)

角度触发$digest(通常)本身。您的$watch应该&#34;只是工作&#34;。

哦 - 如果你真的需要自己启动$ digest循环,你应该使用$scope.apply()而不是直接调用digest。

幕后真正发生的事情是各种事情实际上触发$digest,包括ng-click事件,超时,观察者,长轮询,websockets,http调用,承诺 - 任何改变角度管理的内部应用程序状态(通过&#34;脏检查&#34;)。有关详细信息,请参阅此处:https://www.sitepoint.com/understanding-angulars-apply-digest/https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ digest

答案 2 :(得分:0)

  

要理解Angular上下文,我们需要查看究竟是什么   在里面继续。 $ digest有两个主要组成部分   循环:

当Angular认为值可能会改变时,它会在值上调用$ digest()来检查值是否为“脏”。因此,当Angular运行时运行时,它会查找潜在的更改关于价值。

$watch lists are resolved in the $digest loop through a process called dirty checking, so after the scope expression is evaluated and the $digest loop runs, the $scope’s watch expressions will run dirty checking.

During the $digest cycle, which executes on the $rootScope, all of the children scopes will perform dirty digest checking. All of the watching expressions are checked for any changes, and the scope calls the listener callback when they are changed.

例如

当我们调用$ http方法时,在下一个$ digest循环运行之前不会实际执行。虽然大多数时候我们都会在$ apply块中调用$ http,但我们也可以在Angular摘要循环之外执行该方法。 要在$ digest循环之外执行$ http函数,我们需要将它包装在$ apply块中。

这将迫使摘要循环运行,我们的承诺将按照我们期望的那样解决。

$scope.$apply(function() {
$http({
method: 'GET',
url: '/api/dataFile.json'
});
});

希望这么多理解帮助!