How to load a new page with AngularJS when a user start typing in an input box -


my route /search shows template , related controller showing list of entries database (properly binding data using controller template using $scope variable). if go /search works , shows data.

now have added search box @ top of page. when user starts typing, wherever on website, show results instantly (showing template results).

what angular way that?


here how did it:

my route:

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: '/' }); }]); 

the global layout:

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

the controller:

angular.module('tastypie.controllers')  .controller('searchcontroller', function($scope, search) {    // bind view   $scope.searchresults = [];   $scope.query = '';    // if user not on search page , start typing, move him search page , perform 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 search services returns results   $scope.$on('searchresults', function(object, results){     $scope.searchresults = results;   });  }); 

and template 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> 

ok, understand better want do. here's how try doing it, limited angular experience:

  • define searchservice
  • inject service main controller, handles search text field
  • have main controller set search text value in search service each time changes, , set location /search if it's not case
  • have search controller associated div displaying search results
  • in search controller, inject searchservice
  • in search controller, use $scope.watch() notified each time search text value stored in searchservice modified
  • each time search text value modified, execute http request search results, store results in scope, , let view iterate through results.

Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -