2015-04-01 63 views
0

只有當它的某個屬性等於數組時,我才需要顯示對象。Equal Arrays AngularJS Pro

我在app.js控制器:

app.controller('checkBoxController', function ($scope) { 
    $scope.ingredients= [ 
     {label: 'Egg', value: 1}, 
     {label: 'Milk', value: 2}, 
    $scope.selection=[]; 
    $scope.toggleSelection = function toggleSelection(ingredientLabel) { 
     var idx = $scope.selection.indexOf(ingredientLabel); 
     if (idx > -1) { 
      $scope.selection.splice(idx, 1); 
     } 
     else { 
      $scope.selection.push(ingredientLabel); 
     } 
    }; 
}); 

,併爲它的HTML代碼:

<span style="color:black;" class="selected-item">Selected Items:<span> 
<div ng-repeat="label in selection" class="selected-item"> 
</div> 
<div class="list-group"> 
    <div class="list-group-item" ng-repeat="product in meals.products" ng-show="product.contents==selection"> 
     <h1>{{product.name}}</h1> 
     <meal-gallery></meal-gallery> 
     <meal-tabs></meal-tabs> 
    </div> 
</div> 

和我的產品陣列有{ name: 'Scrambled Egg', contents: "Egg"}。所以我需要展示產品,如果它的內容等於選定的成分。 我沒有問題,只有一個成分像「蛋」,但如果我需要兩個等於選定的內容?

+0

angularjs pro?是某種模塊?看起來你在發佈時在你的代碼中實現了一個錯字,你的數組並不完整。 – 2015-04-01 20:35:27

+0

除非兩個對象字面上是相同的對象,否則不能以這種方式使用indexOf。 'var x = {}; var y = x; x == y; // true''var x = {'name':'pie'}; x == {'name':'pie'}; // false' – 2015-04-01 20:38:30

回答

0

使用過濾器。

<div ng-repeat=product in products |filter: product.a === a && product.b === b> 

您還可以使用過濾功能。這是一個函數,需要一個項目並返回布爾值

+0

我不能只爲產品的內容使用數組嗎?像這樣:{name:'Scrambled Egg',內容:[「Egg」,「Milk」]} – 2015-04-01 20:44:10

+0

是的,看起來更好 – rrrkren 2015-04-01 21:59:18

+0

但我有一個問題。不知怎的,我有我的代碼只有當product.contents ==選擇和「蛋」(從product.content)== [「蛋」]工作。這很奇怪。我不明白是什麼問題 – 2015-04-01 22:38:08

1

這將是最好使用自定義過濾器。

如果添加lodash到您的應用程序,你可以創建一個過濾器,將大跳以下操作:如果所有的產品內容中包含的成分

angular.module('common', []) 
.filter('canBeMadeFrom', function() { 
    return function(product, ingredients) { 
    return _.intersection(product.contents, ingredients).length == product.contents.length'; 
    }; 
}); 

這將返回true

使用像這樣

ng-repeat='product in products | canBeMadeFrom:ingredients' 
+0

但是我只需要在product.contents中返回true,如果其中至少有一個不是 – 2015-04-01 22:36:01

+0

我已經編輯了我的答案以檢查所有產品內容是否在配料陣列 – 2015-04-02 10:29:29