Sangram Sangram - 1 year ago 93
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 Source


<div ng-app="MyApp" ng-controller="MyCtrl">
  <!-- call $ 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">

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



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

      $ = 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); });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download