AngularJS ngRepeat update model

China☆狼群 提交于 2019-12-18 14:53:02

问题


I use ng-repeat to render a html table. My controller looks like so:

app.controller("fooCtrl", function($scope, WebSocket) {
  $scope.foo = [ ... ];

  WebSocket.start(function(data) {
    // this is a callback on websocket.onmessage
    // here is a for loop iterating through $scope.foo objects and updating them
  });
});

As you can see, I am updating the $scope.foo array periodically. However, my view is constructed like so:

<tr ng-repeat="item in foo">
  ...
</tr>

The problem is, when I update foo, it doesn't re-render my table with new data.

How would I go about this problem?


回答1:


Did you wrap the update in

$scope.$apply(function() {
  // update goes here
});

? This should solve the problem.




回答2:


You probably need to call $apply() to force angular to do a digest cycle when you update the list, like:

 WebSocket.start(function(data) {
   $scope.$apply(function(){
      /* your stuff goes here*/
    });
  });



回答3:


Following code work for me, Whenever you get message from socket you just need to bind your code inside $scope.$apply() function

 socket.on = function (e) {

            $scope.$apply(function () {
               // update you UI over here
            });

        };


来源:https://stackoverflow.com/questions/20599877/angularjs-ngrepeat-update-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!