0

I have an array of posts:

.factory('posts', [function(){
  var o = {
    posts: [
        {title: 'post 1', upvotes: 5},
        {title: 'post 2', upvotes: 2},
        {title: 'post 3', upvotes: 15}
    ]
  };
  return o;
}])

and a Controller. I would like to edit all upvotes when clicking a button, so I have the following.

angular.forEach($scope.posts, function(title){
    $scope.posts.push({
            title: "ja"
    });
});

but obviously this is creating new posts. anyone knows how to edit the existing ones? thanks

1
  • pos[index].title ='ja' Commented Nov 19, 2014 at 13:27

1 Answer 1

1

To update the upvotes value of all posts on clicking a button you would have to change your forEach to:

angular.forEach($scope.posts, function(post){
    post.upvotes++;
});

But if it was to be only a specifc one called 'ja' then you would need to so something like this:

angular.forEach($scope.posts, function(post){
    if (post.title === 'ja') {
        post.upvotes++;
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

was looking more for this angular.forEach($scope.posts, function(post){ post.upvotes = 5; }); but you answered my question. thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.