【问题标题】:How to empty form inputs in angular js after submission提交后如何在angular js中清空表单输入
【发布时间】:2016-12-26 19:53:24
【问题描述】:

你好惊人的 Stackoverflow 编码器,请问如何在表单提交后清空 Angular Js 中的表单输入。

下面是我的工作代码

$rootScope.sendNow = function () {
                            if ($rootScope.send_login.username.length < 1)
                                alert("Please enter username");
                            else if ($rootScope.send_login.password.length < 1)
                                alert("Please enter password");
                            else {

                                $http.post($rootScope.server_url + "post_Data", $rootScope.send_login)
                                        .success(function (response)
                                        {
                                            // on success
                                            $('#send_login.username').val('');
                                              $('#send_login.password').val('');

                                            toastr.success('Successful');

                                        }

                                        ).error(function (response)
                                {

                                    alert("sending failed");
                                });
                            }
                        };

我的表格在下面

<input type="text" id="username" name="username" ng-value="send_login.username">

                            <input type="text" id="pass" name="pass" ng-value="send_login.password">
<input type="button" ng-click="sendNow()" value="Send">

与 Ajax 不同,我在下面尝试过,但无法让它工作

 $('#send_login.username').val('');
  $('#send_login.password').val('');

【问题讨论】:

标签: angularjs forms


【解决方案1】:

你应该在输入标签中使用ng-model,比如:

html:

<input type="text" ng-model="name">
<button ng-click="sendData()"> Send</button>

js(angularjs控制器):

$scope.sendData = function (item) {
    $scope.name = "";
}

【讨论】:

    【解决方案2】:

    最好将每个表单字段 ng-modal 作为对象的属性,就像您在“send_login”中所采用的那样。 表单提交后重新初始化这个对象 send_login = {}; 每个字段都将重新初始化。并且未定义的属性不会产生角度错误。

    您应该避免在代码中过多使用 $rootScope。

    【讨论】:

      【解决方案3】:

      您需要将ng-value 更改为ng-model(将角度变量绑定到html 输入)并在ajax 成功时清除绑定变量:

      $http.post('...').success(function (response) {
          $rootScope.send_login = {};
      });
      

      【讨论】:

        猜你喜欢
        • 2019-02-28
        • 2016-10-23
        • 2017-12-13
        • 1970-01-01
        • 1970-01-01
        • 2016-04-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多