Angularjs 表单验证如何在控制器中获取值

Angularjs Form validation How can i get values inside Controller

这是我的Html部分

    <form name="userForm" ng-submit="submitForm()" novalidate>

                        <!-- NAME -->
                        <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
                            <label>Name</label>
                            <input type="text" name="name" class="form-control" ng-model="user.name" required>
                            <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>
                        </div>
  <button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>

控制器

 $scope.submitForm = function (userForm) {
        $scope.master = angular.copy(userForm);
        if ($scope.userForm.$valid) {
            debugger;
            console.log($scope.userForm.name);
            alert('our form is amazing');
            console.log($scope.userForm);
        }

    };

这就是我无法从 Html 获取值到 Controller

的原因

没有从 ng-submit 向 submitForm 函数传递任何参数!并在 submitForm() 中记录 $scope.user 并查看里面的内容!如果什么都没有,初始化 $scope.user ={};在 submitForm() 之外。然后你可以进入 submitForm 函数 $scope.user.name 希望对您有所帮助!

你能试试下面的代码吗?我想你忘了在按钮事件中传递值

如果您不想更改您的代码,您可以在 $scope.master 中找到文本框值(与您的代码相同)

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<form name="userForm" ng-submit="submitForm(user)" novalidate>

  <!-- NAME -->
  <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }">
    <label>Name</label>
    <input type="text" name="name" class="form-control" ng-model="user.name" required>
    <p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>
  </div>
  <button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    
    $scope.submitForm = function (userForm) {
        $scope.master = angular.copy(userForm);
        if ($scope.userForm.$valid) {
            debugger;
            console.log($scope.userForm.name);
            alert(userForm.name)
            alert('our form is amazing');
            console.log($scope.userForm);
        }

    };
});
</script> 

</body>
</html>

不要为函数定义参数。如果您想要用户的价值并获取表单,请在控制器中使用 $scope.user,在您的控制器中使用 $scope.userForm。

$scope.submitForm = function () {
   $scope.master = angular.copy($scope.userForm);
  .
  .
  .
}