删除 ng 重复中的空白项目



我正在使用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 重复中的空白项目。我该怎么做?谢谢。

使用多个条件来检查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>

这应该有效:

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

有两个选项,一个是使用 ng-if 隐藏 ng-重复项,如果 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>

另一个是使用 getCategory 函数进行过滤:

  function getCategories() {
    return (self.boxes || [])
      .map(function (box) { return box.cat1; }).
      .filter(function (box, idx, arr) { 
        return arr.indexOf(box) === idx && box; 
      });
  }

最新更新