让AngularJS页面兼任搜索结果页面

Make AngularJS page double as search results page

本文关键字:搜索结果 AngularJS      更新时间:2023-09-26

我有一个基本的表,我通过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参数。

就像评论说的,这与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>