假设我有这个对象数组:
ctrl.posts = [Object, Object, Object]
每个对象看起来都像这样:
{id:1, post:"post", likes:2}
这些对象像这样绑定(bind)到前端:
<div ng-repeat="post in ctrl.posts">
<span ng-bind="post.post"></span>
<span ng-bind="post.likes"></span>
</div>
从后端,我收到函数 x 的 ID,如下所示:
functionx(id)
我要做的是更新 ctrl.posts
中 id=id
的项目(我需要做的更新是增加对象的 赞数
通过 1).到目前为止,我可以得到这样的帖子:
self.post = $filter('filter')(self.posts, {id: id}, true);
self.post.likes = self.post.likes + 1;
但是知道得到这个之后我要去哪里吗? (我目前有 self.post 是一个变量。我现在如何用 self.post
替换 ctrl.posts
中的帖子?)。
最佳答案
angular.forEach(ctrl.posts, function(post, index){
if(post.id == myId){
post.likes++;
}
});
关于javascript - 如果我有它的 id 值,如何获取和更新数组中的 AngularJS 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33849757/