Skip to content

Instantly share code, notes, and snippets.

@cointilt
Last active August 29, 2015 14:07
Show Gist options
  • Save cointilt/57ae53394e6f61b3cc16 to your computer and use it in GitHub Desktop.
Save cointilt/57ae53394e6f61b3cc16 to your computer and use it in GitHub Desktop.
Angular Filter Contains
<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>
// 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