如果ng-required为true,则angular删除ng-model变量

时间:2015-03-30 08:29:39

标签: angularjs angularjs-validation

如标题所示..如何防止此类操作发生?这是官方网站的link,请参阅示例。变量user.name绑定到第一个输入userName,如果输入为空,则删除对象user.name。如何禁用angularjs的这个功能?

2 个答案:

答案 0 :(得分:1)

尝试ng-model-options="{allowInvalid: true}"更新模型,即使是无效条目。

<input ng-model="user.name" required ng-model-options="{allowInvalid: true}">

答案 1 :(得分:0)

你有2个选项

  1. 从输入标记中删除required,它允许您将空字符串发送回后端
  2. var app = angular.module('app', []);
    
    
    app.controller('MyCtrl', function($scope) {
      $scope.params = {
        user: "John"
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="MyCtrl">
      <input name="userName" ng-model="params.user" />
      <hr/>
      <pre>{{params| json}}</pre>
    </div>

    1. 选项二在将表单发送到后端之前验证您的表单。
    2. var app = angular.module('app', []);
      
      
      app.controller('MyCtrl', function($scope) {
        $scope.user = {
          name: "John"
        };
      });
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      
      
      
      <div ng-app="app" ng-controller="MyCtrl">
        <form name="someForm">
          <input name="userName" ng-model="user.name" required name="userName" />
          <span ng-show="someForm.userName.$error.required">User Name required</span>
          <br/>{{user | json}}
          <br/>
      
          <button type="submit" ng-disabled="someForm.$invalid">Submit</button>
        </form>
      </div>