我的AngularJS应用程序具有以下简化行为:
我创建了一个带有工厂的服务server
模块,名为. 这个server
模块处理我与 websocket 服务器的通信。当此 websocket 连接中发生事件时,我想在我的MainController
.
我的服务:
return function init() {
ws = new WebSocket(...);
ws.onopen(function () {
$rootScope.$broadcast("flash", "websocket connected");
});
};
我的观点:
<article ng-controller=MainController ng-init=init()>
<section ng-show="flash.length > 0">
<p ng-repeat="message in flash">
{{ message }}
</p>
<section>
<section ng-view>
...
</article>
我的控制器:
function MainController ($rootScope, $scope, server) {
$scope.init = function () {
$scope.flash = [];
server.init();
};
$scope.on("flash", function (event, flash) {
$scope.flash.push(flash);
// $scope.$apply("$scope.flash"); <-- if I uncomment this line, I get the error...
console.debug($scope.flash[$scope.flash.length -1]);
});
};
flash
如果我运行此代码,我会在 websocket 连接上收到调试消息,但仅当我单击按钮 fe 或调用该$apply
函数时,才会应用对数组的更改。后者导致“申请已在进行中”的错误。经过一些研究,我确信,调用 to$apply
是没有必要的。
那么:如何以flash
一种立即通知视图有关更改的方式更改数组?