无法更新ng-repeat($ scope。$ apply())中的数组更新视图不 起作用

问题描述 投票:0回答:2

如果在函数内更新数组,则视图不会更新。虽然,如果我在array.log之后调试数组,那么它会显示更新的数组。我在$ timeout内尝试过$ scope.apply()但它仍无法正常工作。

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>

结果:abc1

javascript angularjs arrays angularjs-ng-repeat
2个回答
2
投票

问题是使用Array.prototype.push函数:

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

正如文档中所述:

push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。

它返回数组的长度,并将其放在保存数组的引用变量中并有效地超出它。

相反,只需使用push而无需再次设置数组:

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

0
投票

@Sumit Rana是您准确发布了如何使用它的代码,还是您将其删除以便在此处发布?我问的原因是,我几乎完全一样的问题,除了我没有使用像你这样的计时器。相反,我有一个简单的功能,它应该只是添加一个元素到一个数组。我正在玩那些工作得很好的小提琴。不幸的是,在我的情况下,ng-repeat没有更新。然后事实证明,原因与我(相当复杂)的ng-repeat声明有关:

<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">

问题是我正在读取文件中的所有属性,但“selected”属性除外。这个属性我在加载数据后正在初始化。不幸的是,在更改阵列后我也忘了做这个初始化。因此,该属性不存在于范围内,我总是有一个空列表。

© www.soinside.com 2019 - 2024. All rights reserved.