带有 AngularJS 指令的类似 Google 的搜索框 [英] Google-like search box with an AngularJS directive

查看:25
本文介绍了带有 AngularJS 指令的类似 Google 的搜索框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<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></span><input type="hidden" name="mode" value="web"/>

</表单>

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

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

  • 在登陆页面上直接提交到结果页面
  • 在结果页面上进行搜索而不重新加载页面并将位置更改为正确的参数?

解决方案

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

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

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

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

基本 Plunkr 示例

<小时>

搜索服务

SearchService 将包含用于搜索的有用属性和方法,但您现在只需要一个简单的 Array 来包含搜索结果列表.

myApp.factory('SearchService', function() {var 搜索服务;搜索服务 = {};//将包含搜索结果的数组SearchService.arrSearchResults = [];返回搜索服务;});

<小时>

应用控制器

ApplicationController 作用域将引用 SearchService 以便您可以使用 ng-repeat 并列出搜索的实际内容结果.

myApp.controller('ApplicationController', ['$scope', 'SearchService', function($scope, SearchService) {//创建对 SearchService 的引用并将其添加到//$scope 所以它将在页面上可用$scope.searchService = SearchService;}]);

<小时>

搜索控制器

SearchController 作用域也将引用 SearchService 以便它可以修改 SearchService.arrSearchResults 数组,从而改变将是什么显示在页面上.它还将包含与表单交互的方法.

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

myApp.controller('SearchController', ['$scope', 'SearchService', '$http', '$location', function($scope, SearchService, $http, $location) {//您的搜索输入$scope.blab = "";//你的搜索功能$scope.search = function() {//确保 blab 有内容(仔细检查总是好的)if($scope.blab != "") {//修改 URL 以显示新请求$location.search('q', $scope.blab);//向您的 URL 发出 GET 请求,该请求将//返回数据供您填充$http.get('/someUrl').成功(功能(数据,状态,标题,配置){//这个回调会被异步调用//当响应可用时alert("找到搜索结果!");//假设返回的数据是一个项目列表//或对象项//(即[搜索结果1",搜索结果2",...]SearchService.arrSearchResults = 数据;}).错误(功能(数据,状态,标题,配置){//发生错误时异步调用//或者服务器返回带有错误状态的响应.alert("失败了!没有找到结果!");//清空搜索结果数组//不显示结果SearchService.arrSearchResults = [];});};}]);

<小时>

页面

<头><title>搜索示例页面</title><!-- 在此处插入 Angular.JS 源文件--><body ng-controller="ApplicationController" ng-app="myApp"><!-- ngView --><div role="main" data-ng-view>

<!-- 搜索结果--><div ng-repeat="searchService.arrSearchResults 中的搜索项"><p style="border-bottom: 2px solid #000">搜索结果:<br/>{{searchItem}}</p>

</html>

<小时>

标签

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

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

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

<div ng-if="searchService.typeOfSearch='web'" ng-repeat="searchService.arrSearchResults 中的搜索项"><p style="border-bottom: 2px solid blue">搜索结果:<br/>{{searchItem}}</p>

<!-- 搜索结果 - 图片--><div ng-if="searchService.typeOfSearch='image'" ng-repeat="searchService.arrSearchResults 中的搜索项"><p style="border-bottom: 2px solid red">搜索结果:<br/>{{searchItem}}</p>

我已经更新了 Plunkr 来演示.

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:

on landing page: form with action="results.html" which passes the parameters in the 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.

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

解决方案

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.

Now, the SearchController and ApplicationController are 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.

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

Basic Plunkr Example Here


SearchService

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

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

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

    return SearchService;
  }
);


ApplicationController

The ApplicationController scope will have a reference to SearchService so that you can use ng-repeat and list out the actual contents of the search results.

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 SearchController scope will also have a reference to SearchService so that it can modify the SearchService.arrSearchResults array, thus altering what will be displayed on the page. It will also contain methods to interact with the form.

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

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 SearchService that controls the state of the search, and thus what type of search to run.

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

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

<!-- 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.

这篇关于带有 AngularJS 指令的类似 Google 的搜索框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆