Angularjs基于逗号元素进行过滤

时间:2018-04-23 13:32:28

标签: angularjs

我想为以下json格式值

过滤angularjs
[

{"id":"1","video_title":"Sample1","tags":"2,12,13","featured":"1"},

{"id":"2","video_title":"Sample2","tags":"5,13","featured":"1"},

{"id":"2","video_title":"Sample3","tags":"2,13","featured":"0"}

] 



<ul><li ng-repeat="single in all_json | filter:customFilter"></li></ul>

<a ng-click="filterBasedonTag(2)">Filter</a>

//脚本

 $scope.filterBasedonTag = function(x) {
 $scope.customFilter = x;
}

如果我传递标签值= 2我想只打印video_title&#34; sample1&#34;和&#34;样本3&#34;。 可以过滤。有任何解决方案吗。感谢所有

2 个答案:

答案 0 :(得分:1)

您可以使用... | your_filter : {"anything" : parameters}语法将参数传递到过滤器,其中parameters与范围有关,可以动态更改。以下是一个简单的自定义过滤器示例:

&#13;
&#13;
var app = angular.module('myApp', []);
app.filter('customFilter', function() {
  return function(x, y) {
    var temp = [];
    for (var i = 0; i < x.length; i++) {
      if (x[i].tags.split(',').indexOf("" + y.tag) != -1) {
        temp.push(x[i]);
      }
    }
    return temp;
  };
});
app.controller('namesCtrl', function($scope) {
  $scope.all_json = [{
      "id": "1",
      "video_title": "Sample1",
      "tags": "2,12,13",
      "featured": "1"
    },
    {
      "id": "2",
      "video_title": "Sample2",
      "tags": "5,13",
      "featured": "1"
    },
    {
      "id": "2",
      "video_title": "Sample3",
      "tags": "2,13",
      "featured": "0"
    }
  ]
  $scope.tag = 2;
  $scope.filterBasedonTag = function(tag) {
    $scope.tag = tag;
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="namesCtrl">
  <li ng-repeat="single in all_json | customFilter:{'tag':tag}">
    {{single.video_title}} - {{single.tags}}
  </li>
  <hr>
  <a ng-click="filterBasedonTag(2)">Filter 2 </a><br>
  <a ng-click="filterBasedonTag(5)">Filter 5 </a><br>
  <a ng-click="filterBasedonTag(13)">Filter 13 </a><br>
  <hr> 
  Selected tag: {{tag}}
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用自定义功能。这是评论中重复链接的改编版本。

当心:我写的自定义函数非常简单,并且返回的值只包含一部分条件,因此在这种情况下,2将返回包含2(12,20,32, 200,...)。我建议你自己写一个合适的功能。

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.criteria = 2;
  
  $scope.criteriaMatch = function( criteria ) {
    return function( item ) {
      return item.tags.indexOf(criteria) > -1;
    };
  };
  
  $scope.items =[
{"id":"1","video_title":"Sample1","tags":"2,12,13","featured":"1"},
{"id":"2","video_title":"Sample2","tags":"5,13","featured":"1"},
{"id":"2","video_title":"Sample3","tags":"2,13","featured":"0"}
];
});
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
  <input type="text" ng-model="criteria">
  <div ng-repeat="item in items | filter:criteriaMatch(criteria)">
    {{ item | json }}
  </div>
</body>
</html>