Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 该视图未在AngularJS中更新_Javascript_Angularjs_Data Binding_Angular Services - Fatal编程技术网

Javascript 该视图未在AngularJS中更新

Javascript 该视图未在AngularJS中更新,javascript,angularjs,data-binding,angular-services,Javascript,Angularjs,Data Binding,Angular Services,在事件回调中更新模型时,更新模型属性对视图没有影响,有什么办法解决这个问题吗 这是我的服务: angular.service('Channel', function() { var channel = null; return { init: function(channelId, clientId) { var that = this; channel = ne

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

这是我的服务:

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]);
            };
        }       
    };
});
已在控制器中动态添加发布功能

控制器:

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>
因此,问题是单击按钮可以正确地更新视图,但是当我从频道收到消息时,没有任何情况发生,甚至添加函数也被调用,您缺少$scope。$apply

无论何时从Angular世界之外触摸任何东西,都需要调用$apply来通知Angular。这可能来自:

由$http服务处理的xhr回调 由$DEBER服务处理的setTimeout回调 由指令处理的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服务: