在AngularJs中动态创建过滤器和匹配复选框
我有很多数据点,有几种类型 JSON文件:在AngularJs中动态创建过滤器和匹配复选框,angularjs,angularjs-filter,Angularjs,Angularjs Filter,我有很多数据点,有几种类型 JSON文件: { "items":[ { "id:": 1, "type": "type1", //typeN isn't tied to id=N ... : ... }, { "id:": 2, "type": "anotherType", ... : ... }, {...},{...},{...},... ] } 我想用DOM中的复选框过
{
"items":[
{
"id:": 1,
"type": "type1", //typeN isn't tied to id=N
... : ...
},
{
"id:": 2,
"type": "anotherType",
... : ...
},
{...},{...},{...},...
]
}
我想用DOM中的复选框过滤这些结果。所以首先我想让他们进入DOM。所以我需要在数据中找到唯一的类型。我通过控制器中的此功能执行此操作:
var itemTypeList = function(){
if ($scope.hasOwnProperty('allItems')){ //this is to ensure async load completed
var uniqTypes = [];
for (var i=0 ; i < $scope.allItems.length ; i++){
if (uniqTypes.indexOf($scope.allItems[i].type) < 0){
uniqTypes.push($scope.allItems[i].type);
}
}
$scope.uniqTypes = uniqTypes;
return $scope.uniqTypes;
}
};
输入复选框如下所示
<input type="checkbox" ng-model="Filter.uT" ng-true-value="{{uT}}"/><br/>
问题是过滤器是静态的,我必须手动输入类型。第二个问题是复选框ng model不能像so
ng model=“Filter.{{uT}}”
那样定义。我只能找到静态定义模型的示例。如何更改过滤器和输入ng repeat以使用我已经找到的uniqueTypes(uT)?无法看到整个画面,但您似乎想要这样的东西:
$scope.showItem = function(item){
return item.type === $scope.Filter.item1 ||
item.type === $scope.Filter.type2;
//this is static, and I only typed 2 of the many....
};
<div class="col-md-12" ng-repeat="uT in uniqTypes">
<label>{{uT}}</label>
<input type="checkbox" ng-model="Filter[uT]"/>
</div>
将返回真或假
基本版本的
如果要让它们最初显示,并单击取消隐藏,$scope.Filter
需要首先由键[val]对填充。这可以在动态创建uniqueTypes
列表时完成
此处显示并初步检查了
ng model='Filter[uT]'
未在DOM中计算为ng model='Filter[type1]'
或ng model='Filter[type2]'
。我得到了一个错误:TypeError:在检查一个正在计算为ng model=“Filter['type1']”的框时,无法设置未定义的属性“type1”
。它抛出错误是因为筛选器($scope.Filter)未定义,而不是因为它未计算。您忘记编写$scope.Filter={}代码>在控制器中,不是吗?:)对不知道JS中对象和关联数组之间的差异。所以这需要一些努力<代码>耶代码>现在工作,不耶代码>用于在一年内非常规地介绍CS和编程。。。谢谢我更新了答案,加入了$scope.Filter
<div class="col-md-12" ng-repeat="uT in uniqTypes">
<label>{{uT}}</label>
<input type="checkbox" ng-model="Filter[uT]"/>
</div>
$scope.Filter = {};
$scope.showItem = function(item){
return $scope.Filter[item.type];
};