Lipis Lipis - 2 months ago 10
AngularJS Question

How to update the filtered list in AngularJS without the user's input

I'm using the filter and everything works nicely when a user types in the input box. What I would like though is to update the filtered results through the code (for example to clear the query), without the user's input. I tried to trigger the change event or simply clear the value of the input field, without any success.

Here is my simplest HTML

<div ng-app ng-controller="test">
<input type="text" ng-model="query" placeholder="search..">
<button>Clear</button>
<ul class="unstyled">
<li ng-repeat="item in list | filter:query">
{{item}}
</li>
</ul>
</div>


And here is the JS:

function test($scope) {
$scope.list = [120, 566, 777, 889, 998, 332, 112, 440, 881];

$('button').click(function() {
$('input').val('');
});
}


JSFiddle

What can I do to unfilter the results without deleting the contents of the input using the keyboard, but doing that though the code (like clicking on the clear button)?

Answer

Do not register your event handler via jQuery let ng-click handle that for you.

<button ng-click="clearBox()">Clear</button>


function test($scope) {
    $scope.list = [120, 566, 777, 889, 998, 332, 112, 440, 881];

    $scope.clearBox = function(){
      $scope.query = "";
    };
}

Updated fiddle

Comments