在事件回调中更新模型时更新模型属性对视图没有影响,有解决这个问题的想法吗?
这是我的服务:
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()
功能是在控制器中动态添加的。
控制器:
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'];
View:
<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>
所以问题是,单击按钮会正确更新视图,但是当我从频道收到消息时,什么也没有发生,甚至add()
函数被调用
你失踪了$scope.$apply()
.
每当你接触 Angular 世界之外的任何东西时,你都需要调用$apply
,通知 Angular。这可能来自:
- xhr 回调(由 $http 服务处理)
-
setTimeout
回调(由$defer
服务)
- DOM 事件回调(由指令处理)
对于您的情况,请执行以下操作:
// 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]);
});
};
}
};
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)