[英]Remove blank item in ng-repeat
我正在使用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中的空白項目。 我該怎么做? 謝謝。
這應該工作:
function getCategories() {
return (self.boxes || []).
filter(function (box) { return box.cat1 !== "" });
}
使用多個條件檢查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>
有兩種選擇,一種是使用ng-if隱藏如果cat為空的ng重復項:
<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>
另一個是使用getCategories函數進行過濾:
function getCategories() { return (self.boxes || []) .map(function (box) { return box.cat1; }). .filter(function (box, idx, arr) { return arr.indexOf(box) === idx && box; }); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.