AngularJS 视图在模型更改时未更新

AngularJS view not updating when model changed

首先,我在 Whosebug 中查看了有关它的其他问题,并阅读了很多答案,但仍然无法解决我的问题。

我正在使用 Angular Material,但我在视图和模型同步方面遇到了问题。

这是我的控制器代码:

$scope.getQuestionByDateRange = function (range) {
     QuestionService.getQuestions(1, 'week', 10, function (response) {
         $scope.questions = response.data;
     })
}

这是我的查看代码:

<ul>
   <li ng-repeat="question in questions">{{question.title}}<li>
<ul>

当我更新控制器中的 $scope.questions 变量时,我的视图正确地呈现了模型。

但是当我再次更新时$scope.questions:我的模型得到了更新(我可以在控制台日志中看到变化)但是视图没有。

我对此进行了研究,并找到了 $scope.$apply$scope.$digest$scope.$evalAsync 等解决方案,但无法解决我的问题。

怎么了?

您可以使用 $watch 方法执行此操作:

$scope.$watch('questions', function(){
  $scope.getQuestionByDateRange(range);
});

每次修改$scope.question时都会触发$watch方法

您遇到的问题是您要替换整个阵列,这似乎会导致 Angular 出现问题。

$scope.getQuestionByDateRange = function (range) {
     QuestionService.getQuestions(1, 'week', 10, function (response) {
         $scope.questions.push.apply($scope.questions, response.data);
     });
}

这里的问题是整个对象都被替换了(所以它失去了对视图的绑定)。

我不会替换整个对象;只需替换它的元素。

$scope.questions = $scope.questions || []; 
$scope.getQuestionByDateRange = function (range) {
 QuestionService.getQuestions(1, 'week', 10, function (response) {
     $scope.questions.length=0; // Reset the array
     $scope.questions.push.apply($scope.questions, response.data);
 })
}