如何在ng-click事件上调用http请求?

时间:2013-09-19 11:33:45

标签: angularjs

我在前端使用angularjs。我在index.html上有两个输入框(即名字和姓氏)和一个按钮。在单击按钮(ng-click =“search()”)上,我想调用带有first-name和last-name作为参数的http GET请求。然后我想在其他DIV标签的同一页面中显示响应。我怎么做到这一点?

1 个答案:

答案 0 :(得分:17)

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