首先,你的模型不正確。您需要的是用戶根據條件篩選的項目列表 - 在本例中爲顏色。
在這種情況下,您不應該將active
屬性放在每個對象上。相反,你應該做的是:
步驟1
定義模型:
$scope.colors = [
{
id: 1,
name: "red"
},
{
id: 2,
name: "blue"
},
{
id: 3,
name: "green"
},
{
id: 4,
name: "red"
}
];
請注意,我沒有添加active
屬性爲每個對象呢。
步驟2
接下來,定義用於跟蹤的有源濾波器的另一種模式:
$scope.activeFilters = [];
最初,這將是空的,但它條目將被添加/移除此取決於選擇每個濾波器的狀態。
步驟3 然後,您有一個功能,將通知如果該複選框被激活或不
$scope.isChecked = function (item) {
return $scope.activeFilters.indexOf(item) !== -1;
};
步驟4
您然後定義將添加/移除過濾器的項目的功能:
$scope.toggleFilter = function (filterItem) {
//Check if the filter item already exists in the list of active filters
if ($scope.activeFilters.indexOf(filterItem) !== -1) {
//Yes, the filter item already exists.
//Since we are in toggle mode, we remove the item from the active filters
$scope.activeFilters.splice($scope.activeFilters.indexOf(filterItem), 1);
} else {
//No entry does not exist.
//Since we are in toggle mode, we add the entry to the list
$scope.activeFilters.push(filterItem);
}
};
每次任何複選框設置/取消設置,您可以調用此函數。
步驟5
接下來,定義,其基於所述有源濾波器的濾波器數據的功能:
$scope.filterData = function() {
//This will be the model that will be used to display the final or
//filtered data
//Reset it each time this is called
$scope.filteredColors = [];
//If there are no active filters, show all the colors
if ($scope.activeFilters.length === 0) {
$scope.filteredColors = $scope.colors;
} else {
for (var i = 0; i < $scope.colors.length; i++) {
//Check if the color name is requested in the active filter
if ($scope.activeFilters.indexOf($scope.colors[i].name) !== -1) {
//The color has been actively set in the filter. Display it
$scope.filteredColors.push($scope.colors[i]);
}
}
}
};
//When the controller is initialized, we need to call the above function once to
//get the colors to display. Since no filters are active initially, all colors
//will be shown
$scope.filterData();
步驟6
每次有源濾波器發生變化,則需要重新計算顏色以顯示 - 一個簡單的手錶就足夠了
$scope.$watch('activeFilters.length', function() {
//Check for invalid values
if ($scope.activeFilters === null || $scope.activeFilters === undefined) {
//Nothing to do
return;
} else {
//Re-calculate the colors to display
$scope.filterData();
}
});
因此,每次設置/重置過濾器時,將重新計算要顯示的顏色列表。
步驟7
現在需要將包含獨特的色彩模式 - 用於過濾
$scope.uniqueColors = [];
for (var j = 0; j < $scope.colors.length; j++) {
if ($scope.uniqueColors.indexOf($scope.colors[j].name) === -1) {
//The color does not exist. Add it
$scope.uniqueColors.push($scope.colors[j].name);
}
}
最後一步
的觀點 - 基於模型和功能,我們已經定義此前,您現在需要相應地定義您的視圖。編輯:Here是一個相同的小提琴。
預定義顏色還是取決於從服務器發送的數據? – Chandermani