Angular.js表单验证如何在Controller中获取值

时间:2018-09-23 09:53:11

标签: angularjs angularjs-validation

这是我的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向控制器获取值

3 个答案:

答案 0 :(得分:0)

在ng-submit的SubmitForm函数中没有传递任何参数!然后将$ scope.user记录在submitForm()中,看看里面有什么!如果什么也没发生,请初始化$ scope.user = {};。在SubmitForm()之外。然后,您可以进入SubmitForm函数$ scope.user.name 希望对您有帮助!

答案 1 :(得分:0)

您可以尝试以下代码吗?我认为您忘了在按钮事件中传递值

如果不想更改代码,可以在$ 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>

答案 2 :(得分:0)

请勿定义功能参数。如果需要user的值,请在控制器中使用$ scope.user,要获取表单,请在控制器中使用$ scope.userForm。

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