我正在使用AngularJS,我有data.json文件:
<li ng-repeat="cat in ctrl.getCategories()">
<input type="checkbox" name="{{cat}}" ng-model="ctrl.filter[cat]" id='{{$index}}' class='chk-btn styled-checkbox' ng-click="removeAnother();"/>
<label for='{{$index}}'>{{cat}}</label>
</li>
但第一项是空白的,因为它没有任何类别:
{"index":0,"cat1":"","class":"test"},
这就是功能:
function getCategories() {
return (self.boxes || []).
map(function (box) { return box.cat1; }).
filter(function (box, idx, arr) { return arr.indexOf(box) === idx; });
}
我需要删除ng-repeat中的空白项目。我该怎么做?感谢。
答案 0 :(得分:0)
这应该有效:
function getCategories() {
return (self.boxes || []).
filter(function (box) { return box.cat1 !== "" });
}
答案 1 :(得分:0)
使用多个条件检查cat1
是否为空。
function getCategories() {
return (self.boxes || []).
map(function (box) { return box.cat1; }).
filter(function (box, idx, arr) { return arr.indexOf(box) === idx && box !== ''; });
}
var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
var self = this;
self.getCategories = getCategories;
self.boxes = [
{"index":0,"cat1":"","class":"test"},
{"index":0,"cat1":"1","class":"test"},
{"index":0,"cat1":"2","class":"test"},
]
function getCategories() {
return (self.boxes || []).
map(function (box) { return box.cat1; }).
filter(function (box, idx, arr) { return arr.indexOf(box) === idx && box !== ''; });
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
<li ng-repeat="cat in ctrl.getCategories()">
<input type="checkbox" name="{{cat}}" ng-model="ctrl.filter[cat]" id='{{$index}}' class='chk-btn styled-checkbox' ng-click="removeAnother();"/>
<label for='{{$index}}'>{{cat}}</label>
</li>
</div>
答案 2 :(得分:0)
有两个选项,一个是使用ng-if隐藏重复项目,如果cat为空白:
<li ng-repeat="cat in ctrl.getCategories()">
<div ng-if="cat">
<input type="checkbox" name="{{cat}}" ng-model="ctrl.filter[cat]" id='{{$index}}' class='chk-btn styled-checkbox' ng-click="removeAnother();"/>
<label for='{{$index}}'>{{cat}}</label>
</div>
</li>
&#13;
另一个是使用getCategories函数进行过滤:
function getCategories() {
return (self.boxes || [])
.map(function (box) { return box.cat1; }).
.filter(function (box, idx, arr) {
return arr.indexOf(box) === idx && box;
});
}
&#13;