我最近开始使用 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() 函数之外,它就会执行,但会在加载页面后立即执行。
任何人都可以帮助我在按下按钮时让它工作吗?
最佳答案
由于您想使用 Angular 并且在 View 中使用 ng-model,因此您应该在按钮上使用 ng-click:
<button ng-click="sendData()">Click me</button>
更好的是,您可以在表单上使用 ng-submit 并使用提交按钮。
在你的 Controller 中你会看到这样的东西:
$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;
});
}
关于javascript - AngularJS - 表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31976605/