Jimi
Jimi

Reputation: 1897

Angularjs ng-repeat not updating after array update

I'm not sure what I'm missing here but I'm trying to update a value inside an array, and then have this reflected in the repeater. Do I need to make a copy or something before applying the update in order for Angular to show the changes?

---sample json

  "lists": [
       {
        "name": "one",
        "enabled": true
       },
       {
        "name": "two",
        "enabled": false
       }
    ]

!-- code

setTimeout(function(){
    $scope.$apply(function(){
    $scope.lists[1].enabled = true;
});
},1);

!--- html

<span data-ng-repeat="list in lists | filter: {enabled: true}"></span>

Upvotes: 2

Views: 1890

Answers (3)

lui1000
lui1000

Reputation: 89

Add your lists variable to the $scope inside your controller like this:

$scope.lists = [{
    "name": "one",
    "enabled": true
   },
   {
    "name": "two",
    "enabled": false
   }];

You also have to add something inside the <span>, because the Html you posted would not display anything. (You need to do something inside the <span> tag in order to show something)

<span ng-repeat="list in lists | filter:{enabled: true}">{{list.name}}</span>

Now when you update the lists variable, this will be reflected in the Html immediately. Works fine for me. Hope i could help!

Upvotes: 0

lulu88
lulu88

Reputation: 1714

From the "other controller" you are talking about broadcast an event:

 $rootScope.$broadcast('listChange', listArray);

Then in the controller that controls your $scope.lists value, listen for the event:

  $scope.$on('listChange', function(event, list) {

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

    });

Upvotes: 7

leedotpang
leedotpang

Reputation: 106

It might help if you use angulars built-in timeout function $timeout.

$timeout(function(){
    $scope.lists[1].enabled = true;
},1);

Documentation here: https://docs.angularjs.org/api/ng/service/$timeout

Upvotes: 1

Related Questions