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 af
you can make it as Michel Tome wrote just more generic way.
<input type="search" ng-model="search" placeholder="Search for fruits!" />
<ul>
<li ng-show="isSimilar($event)">Banana</li>
<li ng-show="isSimilar($event)">Apple</li>
<li ng-show="isSimilar($event)">Orange</li>
</ul>
And in the JS take the text from the event.
$scope.isSimilar = function ($event) {
var text = $event.target.textContent;
var pattern = new Regexp(text, "gi")
return pattern.test($scope.search);
}
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 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 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;
}