gpt4 book ai didi

javascript - Angular - 在 Controller 中使用表单发布值

转载 作者:行者123 更新时间:2023-11-28 13:14:49 25 4
gpt4 key购买 nike

我正在用 AngularJS 编写我的第一个应用程序,而且我对 javascript 很陌生。我有一个简单的问题:

如何在 Angular Controller 中使用 html 表单中的 POST 值?

我有一个表单(为了便于阅读,我删除了 CSS 和验证内容):

<form name="signupForm" novalidate>

<input type="text" placeholder="Name..." ng-model="name" name="name" required />

<input type="email" name="email" ng-model="email" placeholder="Email..." required>

<input type="password" placeholder="Password..." ng-model="password" name="password" required ng-minlength="7" ng-maxlength="50"/>

<button type="button" ng-click="auth.signup()">Sign Up</button>

</form>

我有一个 Controller (没有错误),其功能看起来有点像这样:

    function SignupController($http, $scope, $rootScope, $location) {

vm.signup = function(name, email, password, onSuccess, onError) {

$http.post('http://myapi.com/api/authenticate/signup',
{
name: name,
email: email,
password: password
}).then(function(response) {
// etc
});
}

现在,如何将表单中的名称、电子邮件、密码值分配给 Controller 中的名称、电子邮件、密码?

谢谢。

最佳答案

当您使用 ng-model="email"设置输入时,您只需调用 $scope.email 即可访问 Controller 中的这些变量值。

Case-1: For single value

HTML

<input type="text" ng-model="email" />

Angular Controller

console.log($scope.email);

Case-2: For multiple values

HTML

<input type="text" ng-model="user.firstname" />
<input type="text" ng-model="user.lastname" />
<input type="text" ng-model="user.email" />

Angular Controller

//This will print the all the values (firstname, lastname, email) contains user as object.
console.log($scope.user);

请检查此工作片段以查看实时示例

var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.user = {};
$scope.signup = function(){
console.log($scope.user);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<form name="signupForm" ng-controller="FormCtrl" ng-submit="signup()">
<input type="text" placeholder="Name..." ng-model="user.name" name="name" required />
<input type="email" name="email" ng-model="user.email" placeholder="Email..." required>
<input type="password" placeholder="Password..." ng-model="user.password" name="password" required ng-minlength="7" ng-maxlength="50"/>
<button type="submit">Sign Up</button>
</form>
</body>

关于javascript - Angular - 在 Controller 中使用表单发布值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39488870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com