Last active
August 29, 2015 14:07
-
-
Save cointilt/57ae53394e6f61b3cc16 to your computer and use it in GitHub Desktop.
Angular Filter Contains
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div ng-app="myApp"> | |
<ul ng-controller="myCtrl"> | |
<li ng-repeat="item in items | contains:'id':showList">{{ item.title }}</li> | |
<!-- | |
now instead of showing all items, it will only show list items with the id of 2 or 4 like below: | |
<li>two</li> | |
<li>four</li> | |
--> | |
</ul> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create app | |
angular.module('myApp', []) | |
// controller to make it more real :) | |
.controller('myCtrl', function ($scope) { | |
// list of ids to only show | |
$scope.showList = [2, 4]; | |
// list of items | |
$scope.items = [{ | |
id: 1, | |
title: 'one' | |
}, { | |
id: 2, | |
title: 'two' | |
}, | |
{ | |
id: 3, | |
title: 'three' | |
}, | |
{ | |
id: 4, | |
title: 'four' | |
}]; | |
}) | |
// the contains filter | |
.filter('contains', function () { | |
return function (items, key, haystack) { | |
if (haystack === undefined || ! haystack) { | |
haystack = key; | |
key = false; | |
} | |
return items.filter(function (item) { | |
return _.contains(haystack, key ? item[key] : item); | |
}); | |
}; | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment