我最近开始使用AngularJS,即使我能够在网页加载时通过$ http发送数据,但是当按下按钮时我无法执行此操作。我的代码:
<div ng-app="myApp" ng-controller="myCtrl">
Username: <input type="text" id="u" ng-model="username"><br>
Password: <input type="text" id="p" ng-model="password"><br>
Email: <input type="text" id="e" ng-model="email"><br>
First Name: <input type="text" id="fn" ng-model="firstName"><br>
Last Name: <input type="text" id="ln" ng-model="lastName"><br>
<br>
<button onclick="sendData()">Click me</button>
<br>
{{status}}
</div>
<script>
var app = angular.module('myApp', []);
var arr = new Array();
function sendData() {
arr[0] = document.getElementById("u").value;
arr[1] = document.getElementById("p").value;
arr[2] = document.getElementById("e").value;
arr[3] = document.getElementById("fn").value;
arr[4] = document.getElementById("ln").value;
app.controller('myCtrl', function($scope, $http) {
$http.post("../signup.php", {'data' : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
});
}
</script>
使用该代码,app.controller中的函数不会执行,但如果我把它放在sendData()函数之外,它会执行,但是在加载页面之后。
当按下按钮时,有人可以帮助我让它工作吗?
答案 0 :(得分:3)
如果您想使用棱角分量,并且在视图中使用ng-model,则应使用按钮点击按钮:
<button ng-click="sendData()">Click me</button>
更好的是,您可以在表单上使用ng-submit并使用提交按钮。
在您的控制器中,您将拥有以下内容:
$scope.username = '';
$scope.email = '';
// better have an user object here so you will not have n variables ...
$scope.sendData = function() {
var arr = [];
arr[0] = $scope.username;
arr[1] = $scope.email;
//........
$http.post("../signup.php", {data : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
}
答案 1 :(得分:1)
您需要在控制器范围内定义功能
HTML
<button ng-click="sendData()">Click me</button>
JS
app.controller('myCtrl', function($scope, $http) {
$scope.sendData = function(
$http.post("../signup.php", {'data' : arr})
.success(function(response) {
$scope.status = response.status;
$scope.description = response.description;
$scope.content = response.content;
});
}
});