2

私のルート /search は、データベースからのエントリのリストを表示しているテンプレートと関連するコントローラーを示しています ($scope 変数を使用して、コントローラーからテンプレートにデータを適切にバインドします)。したがって、/search に移動すると、機能してデータが表示されます。

これで、ページの上部に検索ボックスが追加されました。ユーザーが入力を開始すると、Web サイトのどこにいても、すぐに結果を表示したいと思います (テンプレートに結果を表示します)。

それを行うAngularの方法は何ですか?


これが私の最終的なやり方です:

私のルート:

App.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', { templateUrl: '<%= asset_path "welcome/index.html" %>' });
  $routeProvider.when('/search', { templateUrl: '<%= asset_path "search/index.html" %>', controller: 'SearchController' });
  $routeProvider.otherwise({ redirectTo: '/' });
}]);

グローバル レイアウト:

<form class="navbar-form navbar-left" role="search" data-ng-controller="SearchController">
  <div class="form-group">
    <input type="text" class="form-control" placeholder="search" data-ng-model="query" />
  </div>
  <button type="submit" class="btn btn-default">Search</button>
</form>

<div data-ng-view></div>

コントローラー:

angular.module('tastyPie.controllers')

.controller('SearchController', function($scope, Search) {

  // Bind to the view
  $scope.searchResults = [];
  $scope.query = '';

  // if the user is not on the search page and start typing, move him to the search page and perform a search
  $scope.$watch('query', function(new_data, old_data) {
    if (new_data == old_data) return;

    if ($location.path().indexOf('/search') < 0)
      $location.path('search');

    $scope.search();
  });

  $scope.search = function() {
    var s = new Search();
    s.query = $('#query').val();
    s.execute();
  };

  // callback from the search services which returns the results
  $scope.$on('searchResults', function(object, results){
    $scope.searchResults = results;
  });

});

テンプレート search/index.html :

<ul class="list-group" ng-init="search()">
  <li class="list-group-item" ng-repeat="result in searchResults">
    <strong>{{result.title_texts}}</strong>
    <br />
    {{result}}
  </li>
</ul>
4

1 に答える 1

0

わかりました。これで、あなたが何をしたいのかがよくわかりました。私の限られた角度の経験で、私がそれをやってみる方法は次のとおりです。

  • SearchService を定義する
  • このサービスを、検索テキスト フィールドを処理するメイン コントローラーに挿入します。
  • このメイン コントローラーは、変更されるたびに検索サービスで検索テキスト値を設定し、まだ設定されていない場合は場所を /search に設定します。
  • 検索結果を表示する div に関連付けられた検索コントローラーを用意する
  • この検索コントローラーに、SearchService を挿入します。
  • この検索コントローラーで$scope.watch()は、SearchService に格納されている検索テキスト値が変更されるたびに通知されるように使用します
  • 検索テキスト値が変更されるたびに、HTTP 要求を実行して検索結果を取得し、結果をスコープに保存して、ビューが結果を反復処理できるようにします。
于 2013-08-20T08:49:17.730 に答える