当从外部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);
};
对于setTimeout的特定情况,您可能希望使用内置的$timeout。在其他情况下(例如……你可以把你的代码包装在一个apply块中,这样就可以把它提升到AngularJS的摘要循环中,像这样:
setTimeout(function () {
$scope.$apply(function(){
//Your Code goes here
}
}, 1000);