如果数组在函数内更新, View 不会更新。不过,如果我在 array.push 之后 console.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
最佳答案
问题在于使用 Array.prototype.push功能:
$scope.openQuestions = $scope.openQuestions.push({value: '2', question: 'abc2'});
正如文档中所述:
The push() method adds one or more elements to the end of an array and returns the new length of the array.
它返回数组的长度,并将其放入保存数组的引用变量中并有效地超出它。
相反,只需使用推送而无需再次设置数组:
$scope.fetchOpen = function() {
$scope.openQuestions.push({value: '2', question: 'abc2'});
}
关于javascript - 无法更新 ng-repeat 中数组更新的 View ($scope.$apply())不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43666461/