2013-02-08 39 views
0

如果我有一個包含我的產品的json數組,並且正在使用ng-repeat在頁面上顯示它們。angular.js綁定篩選結果以選擇輸入

然後我用了兩個選擇框的顏色和大小這是所有工作正常進行過濾,

但是如果我用彩色濾光片的大小選擇框仍顯示爲產品的整個陣列的所有尺寸,怎麼能我根據過濾的內容刷新大小選擇框的內容?

回答

2

廣東話弄清楚如何回覆到以前的線程,對不起:) 這裏是一個修改小提琴:http://jsfiddle.net/q7EkY/7/

$scope.color = ''; 
$scope.size = ''; 
$scope.colors = function() { 
    var colors = []; 
    for (var i = 0; i < $scope.items.length; i++) { 
     if (colors.indexOf($scope.items[i].colour) == -1) colors.push($scope.items[i].colour); 
    } 
    return colors; 
}; 

$scope.sizes = function() { 
    var sizes = []; 
    for (var i = 0; i < $scope.items.length; i++) { 
     if ((!$scope.color || $scope.items[i].colour == $scope.color) && sizes.indexOf($scope.items[i].size) == -1) sizes.push($scope.items[i].size); 
    } 
    return sizes; 
} 

$scope.doFilter = function() { 
    var filter = {}; 
    if ($scope.color) filter.colour = $scope.color; 
    if ($scope.size) filter.size = $scope.size; 
    return filter; 
} 

模板:

<div ng-controller="myCtrl"> 
    <select ng-model="color" ng-options="c for c in colors()"> 
     <option value="">Colour</option> 
    </select> 
    <select ng-model="size" ng-options="s for s in sizes()"> 
     <option value="">Size</option> 
    </select> 
    <div ng-repeat="item in items | filter:by_colour | filter:doFilter()"> 
     {{ item.title }} 
    </div> 
</div> 

我覺得應該有使用過濾值,更清晰的方式_例如.js。

+0

完善謝謝,我實際使用 'code' $ scope.uniqueColours =函數(){ \t \t \t返回_.chain($ scope.products) \t \t \t \t .pluck( 'colour_title') \t \t \t \t .flatten() \t \t \t \t .unique() \t \t \t \t .value(); \t \t}; 獲得我獨特的色彩,但你的小提琴正是我正在尋找。 – 2013-02-08 15:16:51

+0

@Pythonic,你可以「編輯」你的帖子。只需將** Update **或其中的內容顯示爲已更新/更改即可。 – 2013-02-08 16:33:38

+0

@Pythonic,如果items數組中的大小也是一個數組,那麼是否可以做同樣的事情,因此每個產品可以有多個大小? – 2013-02-08 17:24:02

1

你應該在你的範圍創建過濾器功能,並把它作爲一個參數「一|過濾器」 下面是使用這個的一個簡單的例子:

查看:

<div ng-controller="myCtrl"> 
<div ng-repeat="item in items | filter:doFilter()"> 
    {{ item.title }} 
</div> 
<div>Is filter active? <input type="checkbox" ng-model="filterActive"/></div> 

控制器:

var myApp = angular.module('myApp',[]); 

myApp.controller('myCtrl', function ($scope) { 
    $scope.items = [{ 
     title: 'First item', 
     active: true 
    }, { 
     title: 'Second item', 
     active: false 
    }]; 
    $scope.doFilter = function() { 
     if ($scope.filterActive) return { active: true }; 
     return {}; 
    } 
}); 

http://jsfiddle.net/q7EkY/1/

+0

謝謝@Pythonic,你鏈接到錯誤的小提琴了嗎? – 2013-02-08 14:16:24

+0

對不起,右側鏈接[here](http://jsfiddle.net/q7EkY/1/) – Pythonic 2013-02-08 14:19:36

+0

謝謝@Pythonic,我已經更新了小提琴,以包括兩個選擇框。我如何應用doFilter()方法,以便當我用紅色過濾時,尺寸選擇框中只顯示一個尺寸? – 2013-02-08 14:29:18