我正在使用 AngularJS 1.2.0 通过 websocket 创建一个简单的消息传递应用程序。HTML 在列表上使用 ng-repeat 来生成总输出(我正在输入的消息数组)。我正在使用工厂来托管“私有”数据和方法,并且只公开视图模型和函数来操作控制器中的数据:
<form class="form-search">
<input type="text" ng-model="model.input" class="input-large"
placeholder="Enter your message:">
<button type="submit" class="btn" ng-click="sendMessage()">Send</button>
</form>
<ul>
<li ng-repeat="message in model.output track by $index" ng-bind="message"></li>
</ul>
application.controller('MessageCtrl', ['$scope', 'MessageService', function($scope, Service) {
$scope['model'] = Service.view;
$scope.sendMessage = function() {
Service.sendMessage();
};
$scope.$watchCollection(function() {
return Service['view'];
}, function(data) {
$scope['model'] = data;
});
}])
.factory('MessageService', function('Restangular') {
var Service = {
// other private properties
view: {
input: null,
output: []
}
};
openConnection();
function openConnection() {
// retrieves websocket URL over Restangular
// opens websocket
}
function sendMessage() {
// sends input over socket
// promises are resolved and unshifted onto Service['view']['output'].
}
return {
view: Service['view'],
sendMessage: function() {
sendMessage();
}
}
});
一切正常,除了当 Service['view'] 中的输出数组收到新消息时 DOM 的 ng-repeat 没有更新。我试过在这个线程中使用 $watchCollection 作为解决方案:AngularJS:绑定到服务属性的正确方法,但这也不起作用。我可以让 DOM 重新渲染的唯一方法是通过更改输入文本或触发 CSS 中的悬停状态来强制它重新渲染。
鉴于此设置,触发摘要的最佳方法是什么,以便在使用新消息数据解析承诺并未转移到输出数组时立即呈现 DOM?我想避免使用 $rootScope 和触发事件,因为当其他控制器使用工厂时,这会变得非常不干净。