Search code examples
jsonangularjsrotten-tomatoes

How do I search the rotten tomatoes API with AngularJS


I'm trying to create a search of the rotten tomatoes api using angularjs. I want to be able to type the query press enter or go (on a phone) then the api returns the result of the query.

I tried to attach the $scope.search to an input in the view. I know I'm doing something wrong but due to my inexperience I can't think what to do. Looking for someone to kindly point me in the right direction.

View

<input placeholder="Search for it" ng-model="search">

Controller

ctrls.controller('resultsCtrl', function($scope, $http){
    $scope.search = 'query';
    $http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies.json', {
        params: {
             page_limit: '5',
             page: '1',
             q: $scope.search,
             apikey: myKey,
             callback: 'JSON_CALLBACK'
         }
    })
    .success(function (data) {
        $scope.results = data.movies;
    });
});

Solution

  • You will have to use a function for that

    ctrls.controller('resultsCtrl', function($scope, $http){
        $scope.search = 'query';
        $scope.fetchResults = function(){
          $http.jsonp('http://api.rottentomatoes.com/api/public/v1.0/movies.json', {
              params: {
                   page_limit: '5',
                   page: '1',
                   q: $scope.search,
                   apikey: myKey,
                   callback: 'JSON_CALLBACK'
               }
          })
          .success(function (data) {
              $scope.results = data.movies;
          });
        }
    });
    

    and call it from your view

    <form ng-submit="fetchResults()">
        <input placeholder="Search for it" ng-model="search">
        <input type="submit" value="Go"/>
    </form>