我在前端使用 angularjs。我在 index.html 上有两个输入框(即名字和姓氏)和一个按钮。单击按钮 (ng-click="search()") 我想调用一个带有名字和姓氏作为参数的 http GET 请求。然后我想在其他 DIV 标记的同一页面中显示响应。我将如何实现这一目标?
问问题
38554 次
1 回答
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); });
}
}]);
于 2013-09-19T19:27:14.353 回答