我正在尝试使用相同的user_id更新数组中所有对象的布尔属性。在下面,我整理了我的MVC框架,并尝试以尽可能简短的方式呈现代码。

模型:

 var posts = [{id:1, user_id:1, is_following:true},
    {id:2, user_id:1, is_cool:true},
    {id:2, user_id:2, is_cool:false}];


视图:

<div class="list" ng-repeat="post in posts">
 <button ng-click="unCool(post.user_id,$index)"  ng-if="post.is_cool === true">
 Cool
 </button>
 <button ng-click="makeCool(post.user_id,$index)" ng-if="post.is_cool === false" >
 not Cool
 </button>
 <p>{{post.id}}</p>
</div>


控制器:

$scope.makeCool =function(userid, index){
  //this is an ajax request for brevity i excluded the service
  coolService.makeCool(user_id)
        .success(function (data) {
             $scope.posts[index].is_following = true;
   //How to find other indexes with same user id and make them true too
          }).
        error(function(error, status) {
          //do something
      });
}

$scope.unCool =function(userid, index){
  //this is an ajax request for brevity i excluded the service
  coolService.unCool(user_id)
        .success(function (data) {
             $scope.posts[index].is_following = false;
   //How to find other indexes with same user id and make them false too
          }).
        error(function(error, status) {
          //do something
      });
}

最佳答案

此处无需使用Angular,jQuery或lo-dash函数。您可以使用本机Array.prototype.filter方法将数组缩小为仅匹配的元素,而本机Array.prototype.forEach方法可以更新每个匹配的元素。

$scope.posts
  .filter(function(post) {
    return post.user_id === userid;
  }).forEach(function(post) {
    post.is_following = true;
  });

10-06 14:26
查看更多