如何在ng-click事件中调用http请求? [英] how to call http request on ng-click event?

查看:128
本文介绍了如何在ng-click事件中调用http请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在前端使用angularjs.我在index.html上有两个输入框(即名字和姓氏)和一个按钮.在单击按钮(ng-click ="search()")时,我要调用一个以名字和姓氏为参数的http GET请求.然后,我想在同一页面的其他DIV标签中显示响应.我将如何实现呢?

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?

推荐答案

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:

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

这篇关于如何在ng-click事件中调用http请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆