2017-10-18 74 views
2

我使用AngularJS和我有data.json文件:在NG-重複刪除空白項

<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重複中的空白項目。我該怎麼做?謝謝。

回答

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>

0

這應該工作:

function getCategories() { 
    return (self.boxes || []). 
    filter(function (box) { return box.cat1 !== "" }); 
    } 
0

有兩種選擇,一種是使用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; 
 
     }); 
 
    }