まず、モデルが正しくありません。必要なのは、ユーザーが条件 (この場合は色) に基づいてフィルター処理したアイテムのリストです。
このような場合、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);
}
}
最終ステップ
ビュー - 以前に定義したモデルと関数に基づいて、ビューを適切に定義する必要があります。
<label ng-repeat="c in uniqueColors">
<input type="checkbox" ng-checked="isChecked(c)" ng-click="toggleFilter(c)">
{{c}}
</label>
<div ng-repeat="f in filteredColors">
{{f}}
</div>
編集:これは同じフィドルです。