【问题标题】:getting data back to controller from form从表单将数据返回给控制器
【发布时间】:2014-04-06 13:01:03
【问题描述】:

我在下面有这个表格。当我更改文本字段时,它会在此处显示更改

<div>
    {{authform.email}}{{authform.password}}
</div>

但是当我尝试在按钮上通过ng-click="signup()" 提交表单时,它不会向我发送文本字段的值。 下面是我的代码

<div class="col-md-12" ng-controller="authCtrl">


        <div class="row">
            <div class="col-md-14">
                <div class="jumbotron">

                    <form>
                        <div class="createUserDiv"><input type="text" name="email" placeholder="enter your email address" ng-model="authform.email"/></div>
                        <div class="createUserDiv"><input type="text" name="password" placeholder="enter your password" ng-model="authform.password"/></div>
                        <div class="createUserDiv"><input type="text" name="confirmpassword" placeholder="confirm your password" ng-model="authform.confirmpassword"/></div>

                        <p><a class="btn btn-lg btn-success" ng-click="signup()">Splendid!<span
                                class="glyphicon glyphicon-ok"></span></a></p>
                    </form>
                    <div>
                        {{authform.email}} {{authform.password}}
                    </div>
                </div>

            </div>
        </div>

</div>

这是我的 js

angular.module('myAPP')
    .controller('authCtrl', function ($scope, $http, $location) {


        $scope.signup = function() {

            $scope.authform = {};
            $scope.authform.email = "";
            $scope.authform.password  = "";
            $scope.authform.confirmpassword  = "";

            var data = {
                "dataBlob": {
                    "email": $scope.authform.email,
                    "password":  $scope.authform.confirmpassword

                }
            };

      console.log($scope.authform.email); 
    });

我的console.log 出现空...null....我不确定它为什么不将字段绑定到数据。我对 Angular 还很陌生,所以我仍在尝试弄清楚这些事情。

【问题讨论】:

    标签: javascript angularjs angularjs-scope angular-ui-bootstrap


    【解决方案1】:

    像这样统计你的控制器:

    angular.module('myAPP')
    .controller('authCtrl', function ($scope, $http, $location) {
        $scope.authForm = {};
    

    然后更改您的注册方法以执行此操作:

    $scope.signup = function() {
        console.log($scope.authForm);
    }
    

    您的值已经绑定,但是当您调用 $scope.authForm = {};在注册过程中,您将覆盖所有值。

    另外,不要在按钮上使用 ng-click="signup()",请执行以下操作:

    <form ng-submit="signup()">
    

    当用户在输入字段中时,这将允许您实现验证并在 [enter] 按键上提交

    例如,请参阅fiddle

    【讨论】:

    • 您是否摆脱了 signup() 中的前四个 $scope.authform 行?这很明显是导致您的 authform 对象值在您的 console.log() 调用中为空的原因。
    • 我只是在我的答案中添加了一个小提琴,尽管您必须打开控制台才能查看正在记录的数据(确保您在字段中输入了一些内容)
    • 没问题,很高兴为您提供帮助
    猜你喜欢
    • 2023-04-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 2011-01-20
    • 2012-08-29
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多