javascript 带有 AngularJS 指令的类似 Google 的搜索框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28505183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:05:25  来源:igfitidea点击:

Google-like search box with an AngularJS directive

javascriptangularjsangularjs-directiveangularjs-ng-form

提问by Ela

I am writing an application which UI wise is almost exactly like Google. I arrive at landing page I have a search box which on submit directs you to results page. Here you have the same search box and other directives in which you can switch between modes: eg. web, image. Currently I have:

我正在编写一个应用程序,它的 UI 智能几乎与 Google 一模一样。我到达着陆页我有一个搜索框,提交时会将您定向到结果页面。在这里,您有相同的搜索框和其他指令,您可以在其中切换模式:例如。网络, 图片. 目前我有:

on landing page: form with action="results.html" which passes the parameters in the url.

在登陆页面上:带有 action="results.html" 的表单,它在 url 中传递参数。

<form name="search" role="form" action="results.html">
    <div class="input-group input-group-search">

        <input type="text" class="form-control"  ng-model="blab" name="q" required>
        <span class="input-group-addon">
            <button class="btn-search" ng-disabled="search.$invalid">
                <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
            </button>
        </span>
        <input type="hidden" name="mode" value="web"/>
    </div>
</form>

on results I am just using ng-submit="search()" and ng-model on the input. The search box is within the searchController.

在结果上,我只是在输入上使用 ng-submit="search()" 和 ng-model。搜索框位于 searchController 中。

What is the right method for doing this as a custom directive, with the following behaviour:

作为自定义指令执行此操作的正确方法是什么,具有以下行为:

  • On landing page on submit direct to results page
  • On results page make a search without reloading the page and change the location to the right parameters?
  • 在登陆页面上直接提交到结果页面
  • 在结果页面上进行搜索而不重新加载页面并将位置更改为正确的参数?

采纳答案by Pixxl

I run something similar on my site currently. I however did not wrap my search into a directive because it is it's own page.

我目前在我的网站上运行类似的东西。然而,我没有将我的搜索包装到指令中,因为它是它自己的页面。

For how I have it setup, I have a search page site.com/search(which would be your landing page for example) That page has its own controller/view SearchController. On the same page lies a separate container which can essentially list items that are inside an array. Finally, the entire page has an ApplicationController.

对于我如何设置它,我有一个搜索页面site.com/search(例如,这将是您的登录页面)该页面有自己的控制器/视图SearchController。在同一页面上有一个单独的容器,它基本上可以列出数组内的项目。最后,整个页面都有一个ApplicationController.

Now, the SearchControllerand ApplicationControllerare obviously separate and therefore cannot access each-other's properties or methods. What they can do however, is either share a factory/service or broadcast information. For the simplicity of this example we will have them share a service called SearchService.

现在,SearchControllerApplicationController显然是分开的,因此不能访问彼此的属性或方法。然而,他们可以做的是共享工厂/服务或广播信息。为简单起见,我们将让他们共享一个名为SearchService.

If you still wish to use a directive, you can easily turn the SearchControllerinto a directive and utilize the same concept for yourself.

如果您仍然希望使用指令,您可以轻松地将其SearchController转换为指令并为自己使用相同的概念。

Basic Plunkr Example Here

基本 Plunkr 示例在这里



SearchService

搜索服务

The SearchServicewill contain useful properties and methods for searching, but all you need right now is just a simple Arrayto contain a list of search results.

SearchService将包含有用的属性和方法的搜索,但你现在需要的权利仅仅是一个简单的Array包含搜索结果列表。

myApp.factory('SearchService', function() {
    var SearchService;
    SearchService = {};

    // The array that will contain search results
    SearchService.arrSearchResults = [];

    return SearchService;
  }
);


ApplicationController

应用控制器

The ApplicationControllerscope will have a reference to SearchServiceso that you can use ng-repeatand list out the actual contents of the search results.

ApplicationController范围将有一个参考SearchService,这样就可以使用ng-repeat并列出搜索结果的实际内容。

myApp.controller('ApplicationController', [
  '$scope', 'SearchService', function($scope, SearchService) {

      // Create a reference to the SearchService and add it to the 
      // $scope so it will be available on the page
      $scope.searchService = SearchService;

  }
]);


SearchController

搜索控制器

The SearchControllerscope will also have a reference to SearchServiceso that it can modify the SearchService.arrSearchResultsarray, thus altering what will be displayed on the page. It will also contain methods to interact with the form.

SearchController范围也将有一个参考SearchService,以便它可以修改SearchService.arrSearchResults阵列,从而改变究竟会在页面上显示。它还将包含与表单交互的方法。

It will also alter the URL location when a search is executed.

它还会在执行搜索时更改 URL 位置。

myApp.controller('SearchController', ['$scope', 'SearchService', '$http', '$location', function($scope, SearchService, $http, $location) {

    // Your search input
    $scope.blab = "";

    // Your search function
    $scope.search = function() {

    // Make sure blab has content (always good to double check)
    if($scope.blab != "") {

        // Alter URL to show new request
        $location.search('q', $scope.blab);

        // Make a GET request to your URL that will 
        // return data for you to populate
        $http.get('/someUrl').
            success(function(data, status, headers, config) {

                // this callback will be called asynchronously
                // when the response is available

                alert("Search results found!");

                // Assuming the data returned is a list of items
                // or object items
                // (i.e. [ "Search Result1", "Search Result2", ... ]
                SearchService.arrSearchResults = data;

            }).
            error(function(data, status, headers, config) {

                // called asynchronously if an error occurs
                // or server returns response with an error status.

                alert("Something failed! No results found!");

                // Empty the array of search results 
                // to show no results
                SearchService.arrSearchResults = [];
            });
    };
}]);


The Page

这一页

<!doctype html>
<head>
    <title>Search Example Page</title>

    <!-- Insert Angular.JS source files here -->
</head>
<body ng-controller="ApplicationController" ng-app="myApp">

    <!-- ngView -->
    <div role="main" data-ng-view>

    </div>

    <!-- Search Results -->
    <div ng-repeat="searchItem in searchService.arrSearchResults">

        <p style="border-bottom: 2px solid #000">Search Result: <br/>{{searchItem}}</p>

    </div>

</body>
</html>


Tabs

标签

For switching the type of search result (web, image, etc) you can create a variable within the SearchServicethat controls the state of the search, and thus what type of search to run.

要切换搜索结果的类型(网络、图像等),您可以在 中创建一个变量SearchService来控制搜索的状态,从而控制要运行的搜索类型。

SearchService.typeOfSearch = "web";This sets the state to weband thus can be interacted within the page and app.

SearchService.typeOfSearch = "web";这会将状态设置为web,因此可以在页面和应用程序中进行交互。

You can then have various ng-repeatthroughout the page all showing results for different states:

然后,您可以ng-repeat在整个页面中使用各种显示不同状态的结果:

<!-- Search Results - Web -->
<div ng-if="searchService.typeOfSearch='web'" ng-repeat="searchItem in searchService.arrSearchResults">

    <p style="border-bottom: 2px solid blue">Search Result: <br/>{{searchItem}}</p>

</div>


<!-- Search Results - Image -->
<div ng-if="searchService.typeOfSearch='image'" ng-repeat="searchItem in searchService.arrSearchResults">

    <p style="border-bottom: 2px solid red">Search Result: <br/>{{searchItem}}</p>

</div>

I have updated the Plunkr to demonstrate.

我已经更新了 Plunkr 来演示。