【问题标题】:The view is not updated in AngularJSAngularJS 中的视图未更新
【发布时间】:2012-04-28 02:23:17
【问题描述】:

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

这是我的服务:

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() 函数

【问题讨论】:

    标签: javascript angularjs data-binding angular-services


    【解决方案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]);
            });
          };
        }
      };
    });
    

    【讨论】:

    • 这很有帮助,一旦我想到为什么在 DOM/jQuery 事件的情况下必须这样做,这对我来说是有意义的,我能够接受它。
    • 酷。我不知道你可以注入根范围。
    • 对于setTimeout 回调,请改用$timeout 服务:coderwall.com/p/udpmtq
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2016-12-05
    相关资源
    最近更新 更多