私のルート /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>