[英]AngularJS - Best method to trigger digest from outside of Angular
我不太確定標題是最好的描述,但我想知道如果我在Angular摘要循環之外發生了一些事件,觸發摘要循環,最好的方法是什么? 在我正在處理的應用程序中,我正在使用Socket.io來從網絡中的其他應用程序來回傳遞數據。 Socket.io中有一些事件可用於更新當前Controllers $范圍內的模型。 在發生摘要循環之前,這些更改不會反映在UI中。 我不希望調用$ scope。$ apply()以防止遇到Angular已經處於循環中的問題。
我知道我可以使用$ timeout()並將我的函數放在那里並將超時設置為0秒。 這就是我目前使用的,它工作正常,但我想知道這是否是最好的方法?
示例JS
var app = angular.module('MyApp',[]);
var socket = io.connect('http://localhost:3000');
app.controller('MyAppController',['$scope',function($scope) {
$scope.connections = 0;
socket.on('connect',function(sock) {
sock.on('event',function() {
$scope.connections++;
};
};
}]);
示例HTML
<!DOCTYPE html>
<html lang="en" ng-app="MyApp">
<head></head>
<body ng-controller="MyAppController">
<p>Connections: {{connections}}</p>
<script src="angular.min.js"></script>
</body>
</html>
顯然,這是一個非常簡單的,盡可能基本的例子。 它不是正在使用的ACTUAL代碼,但代表了同樣的問題。 當從socket.io引發事件時,$ scope.connections變量會遞增但是UI不反映更改,直到其他東西觸發摘要循環,$ scope。$ apply()被調用,或者我使用$ timeout ()。
再一次,我有適用的代碼,只是想知道最好的方法是什么。
謝謝
每當您知道自己不在摘要循環中時,調用$ scope。$ apply()或$ scope.digest()始終是安全的(並且是最佳實踐)。 你怎么知道的? 任何不通過Angular API完成的異步調用。 這是角度在內部處理這些情況的方式(查看ngEvent指令的代碼)。
僅當您不確定正在運行的代碼是否在“內部”角度時才使用$ timeout。 這應該是非常非常罕見的。 我只需要這一次,我仍然不是很高興...
var app = angular.module('MyApp',[]);
var socket = io.connect('http://localhost:3000');
app.controller('MyAppController',['$scope',function($scope) {
$scope.connections = 0;
socket.on('connect',function(sock) {
sock.on('event',function() {
//wraps your code in a try catch that is handled by angular's error service. Calls $rootScope.$digest()
$scope.$apply(function() {
$scope.connections++;
});
//OR - errors in your code will not be handled by angular
//also calls $rootScope.$digest()
$scope.connections++;
$scope.$apply();
//OR - errors in your code will not be handled by angular
//Only processes watchers for $scope and it's children
//Fastest, but may have unintended consequences.
$scope.connections++;
$scope.$digest();
};
};
}]);
我更喜歡第一個選項,因為它使你的代碼“內部有角度”。 但是,這三個都有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.