I'm using AngularJS and I have data.json file:
<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>
But first item is blank because it has no any categories:
{"index":0,"cat1":"","class":"test"},
And this is the function:
function getCategories() {
return (self.boxes || []).
map(function (box) { return box.cat1; }).
filter(function (box, idx, arr) { return arr.indexOf(box) === idx; });
}
I need remove blank items in ng-repeat. How can I do it? Thanks.
this should work:
function getCategories() {
return (self.boxes || []).
filter(function (box) { return box.cat1 !== "" });
}
use multiple conditions to check the cat1
isn't empty.
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>
There are two options, the one is to use ng-if to hide ng-repeated item if cat is blank:
<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>
And the another one is to use the getCategories function to do the filtering:
function getCategories() { return (self.boxes || []) .map(function (box) { return box.cat1; }). .filter(function (box, idx, arr) { return arr.indexOf(box) === idx && box; }); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.