从外部调用AngularJs方法而不需要$ digest

时间:2014-08-19 07:10:15

标签: angularjs angularjs-scope

从AngularJs外部调用方法时,我需要调用$ digest / $ apply,但我不想处理它。有没有办法做到这一点?

<button ng-click='sayHello()'>greet</button>
{{greeting}}

//This works fine!
$scope.sayHello = function () {
    $scope.greeting = 'Hello!';
};

//This needs a $digest!
$scope.sayHello = function () {
    //setTimeout simulates invokation from outside AngularJs.
    setTimeout(function () {
        $scope.greeting = 'Hello!';
        //I don't want to think about $digest(); 
        //So, how to do this without the $digest?
        $scope.$digest(); //or $scope.$apply();
    }, 1000);
};

1 个答案:

答案 0 :(得分:2)

对于setTimeout的特定情况,您可能希望使用$ timeout内置。在其他情况下(例如,JQuery Events),您可以将您的代码封装在一个应用程序块中,从而将其提升到AngularJS摘要周期中,如下所示:

setTimeout(function () {
  $scope.$apply(function(){
    //Your Code goes here
  }
}, 1000);
相关问题