pet*_*lex 58 javascript data-binding angularjs angular-services
在事件回调中更新模型时更新模型属性对视图没有影响,有什么想法可以解决这个问题吗?
这是我的服务:
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]);
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
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'];
Run Code Online (Sandbox Code Playgroud)
视图:
<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>
Run Code Online (Sandbox Code Playgroud)
所以问题是单击按钮可以正确地更新视图,但是当我收到来自Channel Nothings的消息时,甚至add()会调用该函数
Voj*_*jta 131
你错过了$scope.$apply().
每当你触摸Angular世界之外的任何东西时,你需要打电话$apply,通知Angular.那可能来自:
setTimeout回调(由$defer服务处理)在你的情况下,做这样的事情:
// 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]);
});
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32246 次 |
| 最近记录: |