Reputation: 22747
Assume I have this array of Objects:
ctrl.posts = [Object, Object, Object]
Each object looks similar to this:
{id:1, post:"post", likes:2}
These objects are binded to the front-end like so:
<div ng-repeat="post in ctrl.posts">
<span ng-bind="post.post"></span>
<span ng-bind="post.likes"></span>
</div>
From the back-end, I receive an id to a function x, like so:
functionx(id)
what I have to do is update the item in ctrl.posts
whose id=id
(the update I need to do is to increase the object's likes
by 1). What I have so far is, I can get the post like so:
self.post = $filter('filter')(self.posts, {id: id}, true);
self.post.likes = self.post.likes + 1;
but any idea where I go after getting this? (I currently have self.post is a variable. How would I replace the post inside ctrl.posts
with self.post
now?).
Upvotes: 2
Views: 119
Reputation: 400
You can use pure javscript. Do the following:
var postIndex = ctrl.posts.map(function(item) {return item.id; }).indexOf(myId);
var foundPost = ctrl.posts[postIndex];
Upvotes: 0
Reputation: 4914
angular.forEach(ctrl.posts, function(post, index){
if(post.id == myId){
post.likes++;
}
});
Upvotes: 1
Reputation: 3911
You could use lodash and the map function: lodash map function
Upvotes: 0