Reputation: 759
I have a basic table in which I'm displaying data, as pulled from a database, through AngularJS. I also have a search field that uses AngularJS to filter the data:
<input ng-model="search" id="search" type="text" placeholder="Search" value="">
<div ng-controller="eventsController")>
<table>
<tr ng-repeat="event in events | filter:search">
<td><span ng-bind="event.title"></span></td>
<td><span ng-bind="event.date_start"></span></td>
</tr>
</table>
</div>
<script>
function EventsController($scope, $http) {
$http.get('/api/all-events').success(function(events) {
$scope.events = events;
});
}
</script>
This is great for user-defined searches, but what if I want to run a particular filter upon page load while maintaining the search functionality? Is there a way that I can use AngularJS to automatically filter the results based on a URL parameter (i.e. example.com?search=foo)? Ideally, the value of the the input field would also be set to the URL parameter.
Upvotes: 0
Views: 1579
Reputation: 1446
Like the comments said, this has nothing to do with filter
. It's more about how you organize your code to customize URL path you send to the server. You can try to do it this way:
function EventsController($scope, $http) {
// this field is bound to ng-model="search" in your HTML
$scope.search = 'ALL';
$scope.fetchResults = function() {
var path;
if ($scope.search === 'ALL') {
path = '/api/all-events';
} else {
path = '/search?input=' + $scope.search;
}
// here we send different URL path
// depending on the condition of $scope.search
$http.get(path).success(function(events) {
$scope.events = events;
});
};
// this line will be called once when controller is initialized
$scope.fetchResults();
}
And your HTML code, make sure your controller is on the parent div of the input field and search button. And for the search button, you invoke fetchResults()
when it's clicked:
<div ng-controller="eventsController")>
<input ng-model="search" id="search" type="text" placeholder="Search" value="">
<button ng-click="fetchResults()">Search</button>
<div>
<table>
<tr ng-repeat="event in events | filter:search">
<td><span ng-bind="event.title"></span></td>
<td><span ng-bind="event.date_start"></span></td>
</tr>
</table>
</div>
</div>
Upvotes: 1