2015-08-15 5 views
1

Я пытаюсь обновить логическое свойство всех объектов в массиве с тем же 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   
     }); 
} 

ответ

1

Нет необходимости использовать угловые, функции JQuery или вот-тире здесь ... Вы можете использовать собственный метод Array.prototype.filter, чтобы уменьшить размер массива до только совпадающих элементов и родной Array.prototype.forEach me чтобы обновить каждый соответствующий элемент.

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

это создает избыточную интуицию промежуточный массив. Все можно обрабатывать с помощью одной карты и 'if' внутри –

0

Один из подходов заключается в использовании angular filter. Вам не нужен $index (и, вероятно, не очень хорошая идея, если вы решите фильтровать свой ng-repeat).

$scope.makeCool =function(userid){ 
    coolService.makeCool(userid) 
     .success(function (data) { 
      var posts_to_update = $filter('filter')($scope.posts, function(post) { 
       return post.user_id == user_id; 
      }); 
      // Now iterate through and update the boolean property 
      angular.forEach(posts_to_update, function(post) { 
       post.is_following = true; 
      }) 
      }). 
     error(function(error, status) {   
      //do something   
     }); 
} 

Вы можете сделать что-то подобное для unCool

0

Использование lodash библиотеки вы можете легко сделать эту операцию. первая группа ваши данные по «user_id» property.then с использованием цикла устанавливается истина/ложь в булево property.so ваше логическое свойство будет установлено на «user_id»

0

Это напоминает структуру объекта в posts не согласуется. Я думаю, объект со свойством is_following не должен быть обновлен и получить свойство is_cool назначенного.

В случае независимо логик там чистый JavaScript вопрос. Я приведу код на примере makeCool функции.

coolService.makeCool(user_id) 
    .success(function (data) { 
     $scope.posts[index].is_following = true; 
     $scope.posts.map(function(post){//iterate all posts 
       if(post.user_id === user_id && post.hasOwnProperty('is_cool')){//and for those that belong to same user and already have property is_cool 
         post.is_cool = true;//set coolness 
       } 
      }); 
     }). 
+1

. Карта создает ненужный промежуточный массив здесь. Foreach - это функциональность, которую вы ищете. ;) – rrowland

Смежные вопросы