SilentDev
SilentDev

Reputation: 22747

How do I get and update an AngularJS object in an array, if I have it's id value?

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

Answers (3)

peso_junior
peso_junior

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

Loupax
Loupax

Reputation: 4914

angular.forEach(ctrl.posts, function(post, index){
    if(post.id == myId){
       post.likes++;
    }
});

Upvotes: 1

trees_are_great
trees_are_great

Reputation: 3911

You could use lodash and the map function: lodash map function

Upvotes: 0

Related Questions