Angularjs在控制器中过滤。如何过滤不是null,undefined和false值?

时间:2015-07-23 06:20:46

标签: javascript angularjs

我有一个数组:

        var array = [
            {"name": "name1", "value": null},
            {"name": "name2", "value": 3},
            {"name": "name3", "value": false},
            {"name": "name4", "value": undefined},
            {"name": "name5", "value": "some text"}
        ];

现在我想在我的角度控制器中过滤此数组以获取具有值的项目 -

{"name": "name2", "value": 3}

{"name": "name5", "value": "some text"}

所以,我尝试这种方式(并且它不起作用):

data = $filter('filter')(data, { value: emptyOrNull(value) });
function emptyOrNull(value) {
    return !(value === null || value === undefined || value === false);
}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

一种简单而有效的方法,可以解决每一个问题,它只是棘手的方式,但可以帮助你。它将处理所有null, undefined, (''),false`

就这样做

<强> <span ng-repeat="entry in ctrl.array | filter:!!entry.value ">{{entry.name}} </span>

working plunkr

<强>的script.js

(function(angular) {
  'use strict';
angular.module('FilterInControllerModule', []).
  controller('FilterController', ['filterFilter', function(filterFilter)  {

    this.array = [{
    "name": "name1",
    "value": null
}, {
    "name": "name2",
    "value": 3
}, {
    "name": "name3",
    "value": false
}, {
    "name": "name4",
    "value": undefined
}, {
    "name": "name5",
    "value": "some text"
}];

  }]);
})(window.angular);

也可以使用自定义过滤器..

.filter('customFilter',function(){
    return function(val,input){
      var result =[];
      angular.forEach(val,function(res){
        if(res.value && res.value.length || res.value){
           result.push(res);
        }

      });
      return result;

    }

  })

<强>的index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example29-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
  <script src="script.js"></script>



</head>
<body ng-app="FilterInControllerModule">
  <div ng-controller="FilterController as ctrl">
  <div>
    All entries:
    <span ng-repeat="entry in ctrl.array | filter:!!entry.value ">{{entry.name}} </span>
  </div>
  <div>

  </div>
</div>
</body>
</html>

如果您想像代码那样保持简单,那就可以了。

data = $filter('filter')(data, {
    value: !!value
});