我有一个基本表,我通过AngularJS显示从数据库中提取的数据。我还有一个使用AngularJS过滤数据的搜索字段:
<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>
这对于用户定义的搜索非常有用,但是如果我想在保持搜索功能的同时在页面加载时运行特定的过滤器呢?有没有办法可以使用AngularJS根据URL参数自动过滤结果(例如example.com?search=foo)?理想情况下,输入字段的值也将设置为URL参数。
答案 0 :(得分:1)
与评论一样,这与filter
无关。它更多地是关于如何组织代码以自定义发送到服务器的URL路径。您可以尝试这样做:
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();
}
您的HTML代码,请确保您的控制器位于输入字段和搜索按钮的父div上。对于搜索按钮,您可以在点击时调用fetchResults()
:
<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>