Sangram Sangram - 3 months ago 6
AngularJS Question

how to call http request on ng-click event?

I am using angularjs on front end. I have two input boxes on index.html (namely first-name and last-name), and one button. On the click of button (ng-click="search()") I want to call an http GET request with first-name and last-name as parameters. And then I want to show the response in the same page in some other DIV tag. How would I achieve this?

Answer

HTML:

<div ng-app="MyApp" ng-controller="MyCtrl">
  <!-- call $scope.search() when submit is clicked. -->
  <form ng-submit="search()">
    <!-- will automatically update $scope.user.first_name and .last_name -->
    <input type="text" ng-model="user.first_name"> 
    <input type="text" ng-model="user.last_name">
    <input type="submit" value="Search">
  </form>

  <div>
    Results:
    <ul>
      <!-- assuming our search returns an array of users matching the search -->
      <li ng-repeat="user in results">
         {{user.first_name}} {{user.last_name}}
      </li>
    </ul>
  </div>

</div>

Javascript:

angular.module('MyApp', [])
  .controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
      $scope.user = {};
      $scope.results = [];

      $scope.search = function () {
          /* the $http service allows you to make arbitrary ajax requests.
           * in this case you might also consider using angular-resource and setting up a
           * User $resource. */
          $http.get('/your/url/search', { params: user },
            function (response) { $scope.results = response; },
            function (failure) { console.log("failed :(", failure); });
      }
  }]);