Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ngRepeat update model

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?

like image 337
if __name__ is None Avatar asked Dec 15 '13 21:12

if __name__ is None


People also ask

Why is NG-repeat not working?

Solution 1. There are two mistakes in your code: In your table, you have to wrap the properties between {{ and }}, for example {{employee. Fname}} instead of just employee.

How do I remove duplicates in NG-repeat?

You can use unique filter while using ng-repeat . If you use track by $index then unique won't work. ok, I used unique and its working now, thanks!

What is ngRepeat?

Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What is $Index in AngularJS?

Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}. {{item}} </div> </div>


2 Answers

Did you wrap the update in

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

? This should solve the problem.

like image 54
lex82 Avatar answered Oct 10 '22 11:10

lex82


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*/
    });
  });
like image 3
Maxim Shoustin Avatar answered Oct 10 '22 12:10

Maxim Shoustin