这个视图在AngularJS中没有更新

更新模型属性在更新事件callback模型时对视图没有影响,有什么想法来解决这个问题?

这是我的服务:

angular.service('Channel', function() { var channel = null; return { init: function(channelId, clientId) { var that = this; channel = new goog.appengine.Channel(channelId); var socket = channel.open(); socket.onmessage = function(msg) { var args = eval(msg.data); that.publish(args[0], args[1]); }; } }; }); 

publish()函数是在控制器中dynamic添加的。

控制器:

 App.Controllers.ParticipantsController = function($xhr, $channel) { var self = this; self.participants = []; // here publish function is added to service mediator.installTo($channel); // subscribe was also added with publish $channel.subscribe('+p', function(name) { self.add(name); }); self.add = function(name) { self.participants.push({ name: name }); } }; App.Controllers.ParticipantsController.$inject = ['$xhr', 'Channel']; 

视图:

 <div ng:controller="App.Controllers.ParticipantsController"> <ul> <li ng:repeat="participant in participants"><label ng:bind="participant.name"></label></li> </ul> <button ng:click="add('test')">add</button> </div> 

所以问题是点击button会正确更新视图,但是当我收到来自Channel的消息时,就会调用add()函数

你缺less$scope.$apply()

无论什么时候触摸Angular世界以外的任何东西,都需要调用$apply来通知Angular。 这可能来自:

  • xhrcallback(由$ http服务处理)
  • setTimeoutcallback(由$defer服务处理)
  • DOM事件callback(由指令处理)

在你的情况下,做这样的事情:

 // inject $rootScope and do $apply on it angular.service('Channel', function($rootScope) { // ... return { init: function(channelId, clientId) { // ... socket.onmessage = function(msg) { $rootScope.$apply(function() { that.publish(args[0], args[1]); }); }; } }; });