如果数组具有匹配的字符串,则返回Angular自定义过滤器

时间:2017-01-30 21:02:24

标签: javascript angularjs arrays foreach angularjs-filter

我已经抓了一会儿才弄清楚这一点。我觉得自己几乎就在那里,但是不能让最后一块工作正常。这就是我想做的事情。我正在创建一个自定义过滤器,它将遍历我的json数组以查看是否存在"状态"关键,如果"状态" key包含" SUCCESS"字段,它将返回与该数组匹配的所有对象。如果"状态"键不在那里,然后不显示数组对象。我可以看到我的循环看起来正确,因为它确定哪个对象数组包含关键词但是当我尝试打印出我的结果时,我什么也看不见。请帮忙!

这是演示。
https://jsfiddle.net/missggnyc/6r9oophu/20/

HTML

<div ng-app="mySessions">   
    <div ng-controller="sessionController">
  <table>
    <tr>
      <td>Session ID</td>
      <td>Session Name</td>

    </tr>
    <tr ng-repeat="cs in cSessions | successSessionFilter"> 
      <td>{{cs.id}}</td>
      <td>{{cs.session_name}}</td>          
    </tr>
  </table>
</div>

JS

var app = angular.module('mySessions', []);
app.controller("sessionController", ['$scope', function($scope){
        $scope.cSessions = [
    {"id":2,"session_name":"BD20","session_description":"","status":["INPROGRESS"]}, 
    {"id":3,"session_name":"CS03","session_description":"","status":["INPROGRESS", "SUCCESS"]},
    {"id":4,"session_name":"MIS99","session_description":"","status":["FAIL","NOTINPROGRESS"]},
     {"id":5,"session_name":"XGY7","session_description":"","status":["SUCCESS", "NOTINPROGRESS"]},
      {"id":6,"session_name":"DCCC2","session_description":""},
        {"id":7,"session_name":"IUOS33","session_description":""}
    ];
}]);
app.filter('successSessionFilter', function(){
        return function(cObj){          
            angular.forEach(cObj, function(value, key){
                angular.forEach(value, function(v, k){
                    //console.log('k is ' + k + ' and v is '+ v);
                    if(k === 'status'){
                        if(v.indexOf("SUCCESS") > -1){ //if it exists
                            //console.log("SUCCESS exists  "+ v.indexOf("SUCCESS"));
                            //console.log(v);
                            return true;
                        }
                        else { //it the status field isn't there, then don't show the object
                            return false;
                        }                       
                    }
                    else 
                        return false;
                })          
            })
    // console.log(cObj);
        }
    });

2 个答案:

答案 0 :(得分:1)

我们走了

app.filter('successSessionFilter', function(){
  return function(items){           
    var filtered = items.filter(function(item){
      if(item['status'] && item['status'].indexOf('SUCCESS') != -1){
        return item;
      }
    })
    return filtered;
  }
});

演示https://jsfiddle.net/ogycjbkL/

答案 1 :(得分:1)

更简单的方法。只需将tr ng-repeat修改为

即可
<tr ng-repeat="cs in cSessions | filter:'SUCCESS'"> 
          <td>{{cs.id}}</td>
          <td>{{cs.session_name}}</td>          
</tr>

查看实际操作:https://jsfiddle.net/hm4h2esj/