当使用ng-model时,Angular JS清空控制器的输入字段

时间:2016-03-15 19:24:52

标签: angularjs input angularjs-scope angular-ngmodel

我有一个非常简单的表单,有几个输入字段。这是一个:

            <label class="item item-input item-stacked-label">
                <span class="input-label">First Name</span>
                <input type="text" ng-model="signInData.firstName" placeholder="">
            </label>

当我提交表单并且它从AJAX请求返回true时,我想简单地清空输入字段但它不起作用。我可能会遗漏一些简单的事情......

这是我正在尝试清空的控制器代码:

        $scope.signInData.firstName = '';

这是从作用域清空模型,我可以看到,因为我是控制台记录范围对象,但它不会清空值。

我已经谷歌搜索了一段时间,看到了类似$ setPristine方法等的东西,但这一切都没有。

修改

    $http({
      url: 'sign_in_app',
      method: 'POST',
      data: {'firstName': signInData.firstName}
    }).then(function(response) {
      if(response.data.response == 'error'){
        $scope.errorSignIn = 'Sorry, there was an error signing in.';
      }else{
        $scope.errorSignIn = null;
        $scope.signInData.firstName = '';
        $scope.signInForm = null;
      }
    }

编辑 - 表格

    <form ng-submit="signIn(signInData)" id="signInForm" name="signInForm">
        <div ng-bind-html="errorSignIn" class="center error"></div>
        <div class="list">
            <label class="item item-input item-stacked-label">
                <span class="input-label">First Name</span>
                <input type="text" ng-model="signInData.firstName" placeholder="">
            </label>

            <label class="item">
              <button class="button button-full button" type="submit">Sign in</button>
            </label>
         </div>
     </form>

编辑3 - 更新的HTTP CALL

    $http({
      url: '/sign_in/sign_in_app',
      method: 'POST',
      data: {'firstName': $scope.signInData.firstName, 'lastName': $scope.signInData.lastName}
    }).then(function(response) {
      if(response.data.response == 'error'){
        $scope.errorSignIn = 'Sorry, there was an error signing in.';
      }else{
        $scope.errorSignIn = null;
        $scope.signInData.firstName = '';
        $scope.signInForm = null;
      }

    }

2 个答案:

答案 0 :(得分:1)

$setPristine不会清理输入字段。你可以尝试使用 提交表单后$scope.signInData = {};

答案 1 :(得分:1)

试试这个:从signInData移除ng-submit,将$scope.signIn()方法改为不再需要,使用$scope.signInData对象为您设置所有值$http调用(顺便说一下,它可能应该在服务中以保持控制器更加干净并遵循典型的Angular设计模式),然后查看是否仍然存在表单输入未被清除的问题。

我怀疑是因为你从那一点开始传递signInData,你开始操作范围对象的副本,这就是为什么清除属性的行为不像你期望的那样。