Is there any good way of using angular to filter a list WITHOUT ng-repeat? I dont want to use javascript to draw the list at first, but i want to use angular to filter it afterwards.
Example:
<input type="search" ng-model="search" placeholder="Search for fruits!" />
<ul>
<li>Banana</li>
<li>Apple</li>
<li>Orange</li>
</ul>
I want to use the search box to filter the existing html.
(Please dont give any examples with ng-repeat or jQuery in general)
You can write a simple directive to handle show/hide:
app.directive('filterList', function($timeout) {
return {
link: function(scope, element, attrs) {
var li = Array.prototype.slice.call(element[0].children);
function filterBy(value) {
li.forEach(function(el) {
el.className = el.textContent.toLowerCase().indexOf(value.toLowerCase()) !== -1 ? '' : 'ng-hide';
});
}
scope.$watch(attrs.filterList, function(newVal, oldVal) {
if (newVal !== oldVal) {
filterBy(newVal);
}
});
}
};
});
and use it this way:
<input type="search" ng-model="search" placeholder="Search for fruits!" /> {{search}}
<ul filter-list="search">
<li>Banana</li>
<li>Apple</li>
<li>Orange</li>
</ul>
There are a couple of benefits of using a directive:
1). You don't have to put any ngShow/ngIf
directives on every li
.
2). It will also work with a new appended li
elements to the list.
You could use ng-show/ng-hide and compare them to the value of the li's.
Example:
<input type="search" ng-model="search" placeholder="Search for fruits!" />
<ul>
<li ng-show="matches('Banana')">Banana</li>
<li ng-show="matches('Apple')">Apple</li>
<li ng-show="matches('Orange')">Orange</li>
</ul>
And in your js:
$scope.matches = function (text) {
var pattern = new Regexp(text, "gi")
return pattern.test($scope.search);
}
But this is just bad... It's a lot easier with ng-repeat/filter!
You could do this using ngIf
, ngShow
or ngHide
.
<input type="search" ng-model="search" placeholder="Search for fruits!" />
<ul>
<li ng-if="matches('Banana')">Banana</li>
<li ng-if="matches('Apple')">Apple</li>
<li ng-if="matches('Orange')">Orange</li>
</ul>
$scope.matches = function(str) {
return str.indexOf($scope.search) >= 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With