Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - The view is not updated in AngularJS

Updating the model property has no effect on the view when updating the model in event callback, any ideas to fix this?

This is my service:

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() function was added dynamically in the controller.

Controller:

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>

So the problem is that clicking the button updates the view properly, but when I get the message from the Channel nothings happens, even the add() function is called

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are missing $scope.$apply().

Whenever you touch anything from outside of the Angular world, you need to call $apply, to notify Angular. That might be from:

  • xhr callback (handled by $http service)
  • setTimeout callback (handled by $defer service)
  • DOM Event callback (handled by directives)

In your case, do something like this:

// 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]);
        });
      };
    }
  };
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...