Reputation: 126
I am making a request from the server and getting a correct response. That array of objects is $scope.photos
. To add a photo, I make a request get the data back and then I've tried two things but both don't update the $scope in the HTML, while they do - in the script.
I've tried sending an $http request then sends back the whole array of photos, i added them in the javascript $scope.images
array. They were added when I console.logged them but $scope.images
didn't update in the HTML.
I've tried sending the same thing and just adding it to $scope.images
using $scope.images.push(...)
, but still it doesn't work. I get no error.
Here's the code where I declare $scope.images
:
$http({
method: 'GET',
url: '/photos'
}).then(function(data){
$scope.images = JSON.parse(angular.toJson(data.data));
});
Everything here works properly. Here, I'm sending the request and receiving the data. I get the expected array.
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
})
}
The newImage
is logged as well, $scope.images
is getting updated in the script. But there's no difference in the html. Here's the html btw
<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>
Upvotes: 2
Views: 104
Reputation: 527
I remember encounter similar problem before, I don't know my solution can work, but no harm for you to give it a try.
The first thing I try is to renew the reference to the images array
$scope.images = $scope.images.slice();
This could renew the reference to the images array therefor angular able to detect the change happen with the images array
And I always do the trackBy
could be id
or index
, this could help angular improve the ng-repeat
significantly in template.
Upvotes: 1