简体   繁体   中英

AngularJS - Array as filter

How can I setup a filter in an ng-repeat that use strings and an array of strings?

HTML

<div ng-repeat="type in types| orderBy : 'name' | filter:{typology:currTipology}"

JavaScript

var myData = ['string_1', 'string_2', ['string_3', 'string_4']];

I'll use a button for every myData entry to assign the string value to ´currTipology`.

UPDATE I try to better explain my issue. I have a main object data with 6 different 'typology' properties. I need to place 4 buttons: button 1 to 3 corresponds to 1 to 3 'typology' properties; the last button has to filter the 4 to 6 'typology' properties. How should i use filters for last button?

you can use filter by following way

<div ng-repeat="subject in results.subjects | filter:{grade:'C'}">
   <input ng-model="subject.title" />
</div>

See code snippet below for parsing sub-arrays (this will only work for 2 levels-deep arrays). Hope it does the job :)

 var app = angular.module("app", []); app.controller("AppCtrl", function ($scope) { $scope.myData = ['string_1', 'string_2', ['string_3', 'string_4']]; $scope.isArray = function (type) { return typeof type === 'object'; } $scope.isString = function (type) { return typeof type === 'string'; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="AppCtrl"> <div ng-repeat="type in myData"> <div ng-if="isString(type)"> {{type}} </div> <div ng-if="isArray(type)" ng-repeat="subtype in type"> {{subtype}} </div> </div> 

For multiple filter you can do with function some thing like this

<div ng-repeat="employee in employees | filter:{name: companyName} | filter:gradeFilter">

And in controller you have your filter function some thing like

$scope.gradeFilter = function (employee) {
   if(employee.salary > 70000 && employee.exp > 3){ 
      return "Senior"
   } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM