简体   繁体   中英

Unable to update view on array update in ng-repeat ($scope.$apply() ) does not work

The view does not update if the array is updated inside a function. Although, if I console.log the array after array.push then it shows the updated array. I have tried $scope.apply() inside $timeout still it does not work.

JavaScript :

$scope.openQuestions = [];

$scope.openQuestions.push({value: '1', question: 'abc1'});

$timeout(function() {        

  $scope.$apply(function() {            
    $scope.fetchOpen();      
  });

}, 500);

console.log($scope.openQuestions); //shows the updated value

$scope.fetchOpen = function() {
  $scope.openQuestions.push({value: '2', question: 'abc2'});
}

Html

<ul>
 <li ng-repeat = "question in openQuestions">
 <p>{{question.question}} </p>
 </li>
</ul>

Result: abc1

The problem is with the use of the Array.prototype.push function:

 $scope.openQuestions = $scope.openQuestions.push({value: '2', question: 'abc2'});

As said in the docs:

The push() method adds one or more elements to the end of an array and returns the new length of the array.

It returns the length of the array and you put it in the reference variable that hold the array and effectively overrun it.

Instead, just use the push without setting the array again:

$scope.fetchOpen = function() {
  $scope.openQuestions.push({value: '2', question: 'abc2'});
}

@Sumit Rana Is the code which you posted exactly how you are using it, or did you strip it down for posting it here? The reason why I'm asking is, that I had nearly exactly the same issue, except that I was not using a timer like you. Instead I had a simple function which should just add an element to an array. I was playing around with all those fiddles out there which worked fine. Unfortunately in my case ng-repeat did not update. Then it turned out that the reason was correlated to my (fairly complex) ng-repeat statement:

<tr ng-repeat="cmr in cmrs | orderBy:crit:rev:sortByCrit | filter:{selected:search_selected, ip:search_ip, name:search_name, location:search_location}:false as filtered" class="row-eq-height">

The problem was that I was reading all attributes from a file, except the "selected" attribute. This attribute I'm initializing after loading the data. Unfortunately I forgot to do this initialization as well after changing the array. Thus this attribute was not existing in the scope and I always got an empty list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM