kvmu
kvmu

Reputation: 151

Displaying search results using Angular

I'm working on a project and I can't seem to make an API request to Node.js+MongoDB backend using AngularJS.

I have an api route instantiated as such:

app.get("/search_database/:queryString", function(req, res) { ... });

And I'm trying to build something on the frontend using Angular to display these results (in raw JSON) on the browser -- to no avail. API requests from the browser show what I want, but I want to be able to do the same with AngularJS.

Any guidance is appreciated! Thanks!

This is what I have so far:

test.html

<html ng-app="test">
 <head>
    <meta charset="utf-8">
    <title>Angular.js JSON Fetching Example</title>
       <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
     <script> src="core.js"</script>
   </head>

  <body ng-controller="searchCntrlr">
      <div>
      <input class="search-bar-input", ng-model="searchText"/>
      </div>

   {{results}}
   </body>


</html>

core.js

var app = angular.module("test",[]);

app.controller('searchCntrlr', $scope, $http) {
    $http.
      get('/search_database/:searchText/' + $scope.searchText).
      success(function(res){
        $scope.results = res.data;
      });
  };

Upvotes: 4

Views: 3186

Answers (2)

kvmu
kvmu

Reputation: 151

So I figured out my problem -- a bunch of atrocious typos:

Corrected test.html (typo was in in the for the core.js)

<html ng-app="test">
  <head>
    <meta charset="utf-8">
    <title>Angular.js JSON Fetching Example</title>
       <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
     <script src="core.js"></script>
   </head>

  <body ng-controller="searchCntrlr">
    <div>
      <input class="search-bar-input", ng-model="searchText" ng-change="search()"/>
    </div>

    {{results}}
  </body>

</html>

Corrected core.js (completely botched the app.controller syntax before)

var app = angular.module("test",[]);

app.controller('searchCntrlr', ['$scope', '$http', function($scope, $http) {
  $scope.search = function() {
    $http.
    get('/search_database/' + $scope.searchText).
    success(function(res){
      $scope.results = res;
    });

  }
}]);

Upvotes: 1

Sergey Moiseev
Sergey Moiseev

Reputation: 2963

You actually need to call you search on change like this:

var app = angular.module("test",[]);

app.controller('searchCntrlr', $scope, $http) {
  $scope.search = function() {
    $http.
    get('/search_database/:searchText/' + $scope.searchText).
    success(function(res){
      $scope.results = res.data;
    });

  }
};

and call this function in your template:

<input class="search-bar-input", ng-model="searchText" ng-change="search()"/>

Or manually $watch your model and call search there.

Upvotes: 0

Related Questions