I have an input in my view that is bound to a scope property as follows:
<input ng-model="searchTerm">
When text is entered, it can be used to filter a repeater:
<ul>
<li ng-repeat="item in Array | filter: searchTerm"></li>
</ul>
This is fine but I have a problem when I want to filter the array in the controller and repeat on this filtered array instead:
$scope.filteredArray = $filter('filter')($scope.array, $scope.searchTerm);
<ul>
<li ng-repeat="item in filteredArray"></li>
</ul>
When I enter text into my input the searchTerm property does not update the filtered array. I have been able to get it to work by adding an ng-keyup directive to my input to watch for text entered and to update the filtered array accordingly:
In view:
<input ng-keyup="updateFilteredArray()" ng-model="searchTerm">
<ul>
<li ng-repeat="item in filteredArray"></li>
</ul>
In controller:
$scope.filteredArray = $filter('filter')($scope.array, $scope.searchTerm);
$scope.updateFilteredArray = function() {
$scope.filteredArray = $filter('filter')($scope.array, $scope.searchTerm);
}
This works perfectly but it seems strange to me that I need to define both the filteredArray property and the updateFilteredArray method in my controller. Can anyone suggest if this is the way I should be doing it or if there is a way to update the filter without ng-keyup directive? I thought that 2 way data binding would have negated the need for a specific method to update the filtered array, and that when text is entered the property would update wherever it is used in the view and the controller?
searchTermwill be updated. However the filter has already run by that point and will not run again, data-binding doesn't work like that. Applying the filter in your view means data binding is applied and thats why it works. Adding the function handler also works because data-binding means it will callupdateFilteredArrayon every key up event which will in turn filter your array in your controller, data-binding on the array does the rest