我正在向服务器发出请求并得到正确的响应。该对象数组是 $scope.photos
。要添加照片,我请求取回数据,然后我尝试了两件事,但都没有更新 HTML 中的 $scope,而他们在脚本中更新了 $scope。
我试过发送 $http 请求然后发回整个照片数组,我将它们添加到 javascript
$scope.images
数组中。它们是在我控制台记录时添加的,但$scope.images
没有在 HTML 中更新。我试过发送相同的东西,然后使用
$scope.images.push(...)
将它添加到$scope.images
,但它仍然不起作用。我没有收到任何错误。
这是我声明 $scope.images
的代码:
$http({
method: 'GET',
url: '/photos'
}).then(function(data){
$scope.images = JSON.parse(angular.toJson(data.data));
});
这里一切正常。在这里,我发送请求并接收数据。我得到了预期的数组。
var data = {
title: $scope.newImage.title,
url: $scope.newImage.url
}
$http({
method: 'POST',
url: '/add',
headers: {
'Content-Type': 'application/json'
},
data: data
}).then(function(response, callback){
var newPhoto = JSON.parse(angular.toJson(response.data));
$scope.images.push({
title: newPhoto.title,
url: newPhoto.url
});
console.log($scope.images); // the newImage is logged as well
})
}
newImage
也被记录下来,$scope.images
在脚本中得到更新。但是html没有区别。这是 html 顺便说一句
<div class="gallery-item" ng-repeat="image in images | orderBy:
'created_at':true | filter: search">
<img ng-src="{{ image.url }}" class="gallery-item--image" ng-
click="selectedImage = image;openImage($event)" />
<span class="gallery-item--label">{{ image.title }}</span>
</div>
最佳答案
我记得以前遇到过类似的问题,我不知道我的解决方案是否有效,但试一试对你没有坏处。
我尝试的第一件事是更新对图像数组的引用
$scope.images = $scope.images.slice();
这可以更新对图像数组的引用,因此 Angular 能够检测到图像数组发生的变化
我总是做 trackBy
可以是 id
或 index
,这可以帮助 Angular 显着改进 ng-repeat
在模板中。
关于javascript - AngularJS $scope 在 javascript 中更新但在 html 中不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51347960/