$ scope.apply()如何在AngularJS中正常工作? [英] How does $scope.apply() work exactly in AngularJS?

查看:77
本文介绍了$ scope.apply()如何在AngularJS中正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在控制器中更新与DOM表达式({{}})相对应的模型变量.例如

I often updated model variables corresponding to DOM expression ({{}}) within the controllers. e.g.

$scope.myVar = new_value;

有时候,相应的DOM表达式 {{myVar}} 是自动更新的,而其他的则不是.

Some times the corresponding DOM expression {{myVar}} is updated automtically, others it's not.

我知道有时我们需要调用 $ scope.$ apply ,但是...

I understand that sometimes we need to call $scope.$apply but...

  • 我不明白何时我应该称呼它

有时候我称它为确定",但我得到了这个错误(我想是因为它已经被执行了):

Some times I call it (let's say, just to be "sure") but I get this error (I guess since it's already being executed):

错误:[$ rootScope:inprog] http://errors.angularjs.org/1.3.6/ $ rootScope/inprog?p0 =%24digest

Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.6/$rootScope/inprog?p0=%24digest

有任何线索吗?

推荐答案

本质上应用刷新"范围内发生的更改的前端.

Apply essentially "refreshes" your front end with the changes that had occurred to your scope.

大多数时候您不需要申请,因为已经为您完成了.

Most of the time you dont need to do apply as it already is done for you.

假设您执行ng-click();申请已完成.

Lets say that you do an ng-click(); Apply is done for you.

但是,在某些情况下,未触发应用,您必须自己执行.

However, there are cases where apply is not triggered, and you must do it yourself.

带有指令的示例:

 .directive('someCheckbox', function(){
   return {
     restrict: 'E',
     link: function($scope, $el, $attrs) {
       $el.on('keypress', function(event){
         event.preventDefault();
         if(event.keyCode === 32 || event.keyCode === 13){
           $scope.toggleCheckbox();
           $scope.$apply();
         }
       });
     }
   }
 })

我已经更改了范围,但没有为我做任何申请,因此我需要自己做.

I have made changes to my scope but no apply was done for me thus i need to do it myself.

另一个带有超时的示例:

Another example with a timeout:

$scope.getMessage = function() {
  setTimeout(function() {
    $scope.message = 'Fetched after two seconds';
    console.log('message:' + $scope.message);
    $scope.$apply(); //this triggers a $digest
  }, 2000);
};

了解应用和摘要

这篇关于$ scope.apply()如何在AngularJS中正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆