从外部调用AngularJs方法而不需要$digest
当从AngularJs外部调用方法时,我需要调用$digest/$apply,但我不想处理这个问题。有什么好办法吗从外部调用AngularJs方法而不需要$digest,angularjs,angularjs-scope,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.say
<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);
};
问候
{{问候语}
//这个很好用!
$scope.sayHello=函数(){
$scope.greeting='Hello!';
};
//这需要一个$digest!
$scope.sayHello=函数(){
//setTimeout模拟来自外部AngularJs的调用。
setTimeout(函数(){
$scope.greeting='Hello!';
//我不想去想$digest();
//那么,如果没有$digest,如何做到这一点呢?
$scope.$digest();//或$scope.$apply();
}, 1000);
};
对于设置超时的特定情况,您希望使用内置的$timeout。在其他情况下(例如JQuery事件),您可以将代码包装在apply块中,从而将其提升到AngularJS摘要循环中,如下所示:
setTimeout(function () {
$scope.$apply(function(){
//Your Code goes here
}
}, 1000);
你想解决的具体案例是什么?这只是
setTimeout
或setInterval
或更复杂的事情吗?@domakas这是一个更复杂的情况。我有一些(旧的)代码,它调用AngularJs部分。不幸的是,不是我的整个应用程序都是AngularJs。然后你需要按照Christoph所说的做-将所有内容包装在$scope.$apply
中。当你更新angular之外的东西时,它不知道什么时候改变了,所以你需要告诉angular,有些东西改变了,你想更新你的模型/视图/等等。