0

I've the following html list :

<input ng-model="searchValue" />
[...]
<ul>
  <li ng-repeat="item in dataset" ng-if="item.contains(searchValue)">{[item.name]}</li>
  <li noresult>No result ...</li>
</ul>

I prefer use the ng-if than the ng-repeat filter.

And I want to manage the 'noresult' display with the following directive :

directive('noresult', [
    function () {return {
        restrict: "A",
        link : function (scope, element, attrs) {
          scope.$watch(
            function () { return element.parent().children().length; },
            function (length) {
                console.log(length)
                if(length == 1){element.show();}
                else{element.hide();}
            }
          );
        } 
}}]);

When I type something into the input, "console.log" raises each two letters !

Why ? And how can I fix it ?

CheapD AKA Ju
  • 713
  • 2
  • 7
  • 21

2 Answers2

0

May I suggest the following, without using a directive ?

<input ng-model="searchValue" />

<ul>
  <li ng-repeat="item in filteredSet = (dataset | filter:searchValue)" ng-if="showItem(item, searchValue)">{{item}}</li>
  <li  ng-if="filteredSet.length == 0">No result ...</li>
</ul>

And add a function in the controller:

$scope.showItem = function(item, searchVal) {
    return !searchVal || item.indexOf(searchVal) > -1;
}

Fiddle

Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
0

I finally found, adding this to controller:

$scope.$watch('searchValue', function(){
    $timeout(function(){
        $scope.$apply();
}),1});

But it's makeshift job..
I understand that what I wanted to do was not The AngularJS Way.

But, filter's algorithms must be in the object and not just anywhere.
It's The Object Way!

CheapD AKA Ju
  • 713
  • 2
  • 7
  • 21