javascript - 无法更新 ng-repeat 中数组更新的 View ($scope.$apply())不起作用

标签 javascript angularjs arrays angularjs-ng-repeat

如果数组在函数内更新, 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/

相关文章:

javascript - 在 jQuery 中我该怎么说呢?

javascript - 如何比较两个对象数组并更改在两个数组中找到的对象的值?

javascript - 将 AngularJs 添加到 Bootstrap 主题

javascript - 在 AngularJS 模态对话框中是否有处理 "Cancel"的模式?

javascript - CSS指数数

javascript - php 对象转换为 javascript 多维数组

javascript - 减少和连接(或深度展平)数组数组的最快方法

angularjs - 使用 ng-repeat 更新 Angular 模型

javascript - 如何将数组作为参数传递给 Angularjs 中的 $http.get

javascript - 数组如何按两个属性分组?