2015-05-14 100 views
2

我有以下陣列:Angularjs NG-如果選擇NG重複

$scope.selected_items = [ 
    {id: "12345"}, 
    {id: "67890"} 
] 

$scope.list_items = [ 
    { id: "12345", name: "first", more: "data" }, 
    { id: "22222", name: "second", more: "data2" }, 
    { id: "33333", name: "third", more: "data3" }, 
] 

我試圖列出在$scope.list_items誰是id所有項目中不存在$scope.selected_items。我知道我必須做些什麼ng-if,但我不知道該怎麼做。

<div ng-repeat="data in list_items" ng-if="????"> 
    {{ data.name }} 
</div> 

誰能幫我弄清楚這個問題嗎?

回答

2

如果在數組本身內選擇了對象,我建議存儲信息。

例如爲:

的JavaScript

$scope.list_items = [ 
    { id: "12345", name: "first", more: "data", selected: true }, 
    { id: "22222", name: "second", more: "data2" }, 
    { id: "33333", name: "third", more: "data3" selected: true }, 
] 

HTML

<div ng-repeat="data in list_items | filter:{selected:false}"> 
    {{ data.name }} 
</div> 
+1

或者爲什麼不只是'NG重複= 「數據list_items |過濾器:{選擇:假}」'或使用[negated](http://stackoverflow.com/questions/13278371/angularjs-filter-negated)並避免ng顯示 – PSL

+0

感謝羅傑。我修改了我的代碼來處理這個問題。我很欣賞快速答案。什麼是更有效的@PSL? 'ng-if','filter'或者'ng-show' – bryan

+1

@bryan最有效的方法是在控制器中進行過濾(保留過濾列表並將其綁定到DOM並在選擇項目時更新過濾列表)...因此表達式不會在每個摘要循環中被評估。即'$ scope.filtered = $ scope.list_items.filter(function(itm){return!itm.selected})''。如果你在DOM上使用過濾器,ng-if,ng-show他們都會創建一個觀察者。 – PSL

1

既然你提到你不能保持選中狀態的list_items陣列本身英寸你可以在ng-if中調用一個函數,並使用一個函數檢查選中項是否存在。

<div ng-repeat="data in list_items" ng-if="checkItem(data)"> 
    {{ data.name }} 
    </div> 

功能將這個樣子,

$scope.checkItem = function(item) 
    { 
    for(var i=0;i<$scope.selected_items.length;i++) 
    { 
     var sItem = $scope.selected_items[i]; 
     if(sItem.id===item.id) 
     return false; 
    } 
    return true; 
    } 

plnkr鏈接http://plnkr.co/edit/3a4zoKIKFABAmif0fKFt?p=preview

+0

感謝Kathir的工作。我一定會牢記這一點,但它看起來像選定的標籤更有效,所以我修改了我的代碼。 – bryan

+0

我會同意這是有效的方式。 – Kathir

1

如果一定要在你的榜樣分開,你最好的辦法是創建項目的新數組你想要重複。

所以,你會做的是類似的東西:

$scope.newList = []; 
for (var i=0; $scope.list_items.length < i; i++) { 
    for (var s=0; $scope.selected_items.length < s; s++) { 
    if ($scope.selected_items[s].id == $scope.list_items[i].id) { 
     $scope.newList.push($scope.list_items[i]); 
    } 
} 

這將是理想的做什麼我上面的人說,讓所有的這一個對象,只是有一個顯示:真/假標誌在那裏。

1

那麼,正確的模式將是使用AngularJS過濾器。

你剛纔的過濾器添加到您的ngRepeat:

myApp.filter('selectedItems', function() { 
    return function (values, selectedItemsArr) { 
     console.log(values, selectedItemsArr) 

     var arrayToReturn = []; 
     // Loops through the values in the list 
     for (var i = 0; i < values.length; i++) { 

      // Now loops through the selected items array to see if it matches 
      for (var l = 0; l < selectedItemsArr.length; l++) { 
       if (values[i].id === selectedItemsArr[l].id) { 
        arrayToReturn.push(values[i]); 
       } 
      } 
     } 

     return arrayToReturn; 
    }; 
}); 

這裏舉例:http://jsfiddle.net/Nitrium/3vcs445c/1/