一尘不染

该视图未在AngularJS中更新

angularjs

在事件回调中更新模型时,更新模型属性对视图没有影响,是否有任何解决办法?

这是我的服务:

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'];

视图:

<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>

因此,问题在于单击按钮会正确更新视图,但是当我从Channel收到消息时,什么也没发生,即使该add()函数被调用


阅读 211

收藏
2020-07-04

共1个答案

一尘不染

你失踪了$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]);
        });
      };
    }
  };
});
2020-07-04