我想从复选框创建搜索过滤器。因此,如果我检查了牛排和披萨过滤器,那么所有带有牛排或披萨标签的食物都会显示在列表中。
问题在于将标签推送到searchFilter数组的功能,当我检查标签' pizza'大小数组是零,然后推后它是1,但当我检查其他标签'牛排' size数组仍为0,然后在推送后为1。
这是我的代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ion-list>
<ion-item ng-controller="FoodsCtrl" class="list card" ng-repeat="tag in tags">
<div class="item item-head">
<ion-checkbox ng-model="filter.checked" class="checkbox-energized" ng-change="addTag(tag)">{{tag.name}}</ion-checkbox>
</div>
</ion-item>
<ion-list>
</body>
</html>
控制器:
$scope.searchFilters = [];
$scope.addTag = function(tag) {
var check = $scope.filter.checked;
if(check)
{
alert('-' + $scope.searchFilters.length);
$scope.searchFilters.push({
name: tag.name
});
alert($scope.searchFilters.length);
}
else
{
var index = $scope.searchFilters.indexOf(tag.name);
alert(index);
if (index > -1) {
$scope.searchFilters.splice(index, 1);
}
alert($scope.searchFilters.length);
}
};
感谢。
答案 0 :(得分:0)
您可以简化代码。
$scope.changeTag
可以过滤所有已检查的代码(另请参阅 view.html )并将其推送到$scope.searchFilters
。这将处理所有不同的情况,如果元素已经存在于数组中,则无需担心。
<强> controller.js 强>
$scope.tags = [
{
name: "Steak"
},
{
name: "Pizza"
}
];
$scope.searchFilters = [];
$scope.filter = [];
$scope.changeTag = function(tag) {
console.log("Change tag", tag);
var enabledTags = $filter('filter')($scope.tags, {checked: true});
$scope.searchFilters = [];
angular.forEach(enabledTags, function(tag){
$scope.searchFilters.push(tag.name);
});
console.log("$scope.searchFilters", $scope.searchFilters);
};
<强> view.html 强>
<ion-list>
<ion-item class="list card" ng-repeat="tag in tags">
<div class="item item-head">
<ion-checkbox ng-model="tag.checked" class="checkbox-energized" ng-change="changeTag(tag)" checked="item.checked">{{tag.name}}</ion-checkbox>
</div>
</ion-item>
<ion-list>
答案 1 :(得分:0)
只需检查ng-repeat
并将ng-controller
分配给ion-item,这样就可以获得初始化..!
试试这种方式
html:
<ion-content ng-controller="FoodsCtrl" >
<ion-list>
<ion-item class="list card" ng-repeat="tag in tags">
<div class="item item-head">
<ion-checkbox ng-click="addTag(tag)"
class="checkbox-energized"
>{{tag.name}}</ion-checkbox>
</div>
</ion-item>
<ion-list>
控制器:
$scope.searchFilters = [];
$scope.addTag = function(tag) {
var index = $scope.searchFilters.indexOf(tag.name);
if(index === -1)
{
$scope.searchFilters.push( tag.name);
}else{
$scope.searchFilters.splice(index, 1);
}
console.log("$scope.searchFilters after: "+JSON.stringify($scope.searchFilters));
};
希望它在某种程度上有所帮助..!