I have this array of objects :
$scope.posts = [
{
"name" : "name1",
"age" : 12
},
{
"name" : "name1",
"age" : 13
},
{
"name" : "name1",
"age" : 14
}
]
I am ng-repeating this array in my markup as follows:
<div ng-repeat="post in posts">
<span>{{post.name}}</span>
<button ng-click="editPost(post)">Click!</button> <!-- passing post as argument here-->
</div>
Controller:
app.controller('PostController', function($scope, postFactory){
//array is present in controller, just not showing it here
$scope.editPost = function(post) {
postFactory.editPost(post).then(function(data) { //factory having an ajax call which gets new data to be assigned to 'post'
post = angular.copy(data.data)
console.log(post); //here new data is populated successfully
})
}
})
As you can see, when 'editPost' is called, new post data is fetched from an API via a factory and assigned to 'post'(which is the argument to the 'editPost' function). When I console log 'post' after it is assigned the new data, it shows the new data in the console. HOWEVER, in my markup, still the old data is displayed. Any idea why the markup isn't updated? Here's my factory:
app.factory('postFactory', function($http) {
return {
editPost : editPost
}
function editPost(post) {
return $http.post('<api>', post).success(function(response) {
return response.data;
})
}
})
EDIT:
I just noticed something. When I changed:
post = angular.copy(data.data)
to
post.name = data.data.name;
the post gets updated. So, I am guessing mass assignment of an object is not getting updated but when I update an individual property, it gets updated in the template.
datafrom the (deprecated)successfunction, and thepostitself seems to be nested yet another level indata, meaning the api returns a single post nested indata.data.thenis the way to go, but beware that the first argument represents the whole http response (not only the body), and that asuccessthat resolvesresponse.datais equivalent to a then that resolves...response.data.data