【问题标题】:How to manually change the $error values for input tags - Angularjs如何手动更改输入标签的 $error 值 - Angularjs
【发布时间】:2016-06-02 15:55:24
【问题描述】:

我通过 angular $http 提交表单,如果用户绕过 angularjs 验证,我想给出一个错误。我想使用相同的错误标签,就好像他们没有绕过验证一样,userForm.name.$invalid && !userForm.name.$pristine我该如何手动设置这个值?

HTML

  <body>
    <form ng-controller="UserController" ng-model="userForm" name="userForm" ng-submit="createUser()">

      <legend>Create User</legend>

      <label>Name</label> 
      <input type="text" id="name" name="name" ng-model="user.name" placeholder="User Name" required>
      <!-- HERE IS WHERE THE ERROR SHOWS -->
      <p ng-show="userForm.name.$invalid && !userForm.name.$pristine"

      <button class="btn btn-primary">Register</button>

    </form>
  </body>

角度 JS

  $http({
    method : 'POST',
    url : '/create',
    data : user,
    headers : {
      'Content-Type' : 'application/x-www-form-urlencoded'
    }
  })
  .success(function(data) {
    // I want to do something like this 
    name.$invalid = true;
    name.$pristine = false;
  });

我想做一些类似success 函数的事情。因此它将显示错误消息。

【问题讨论】:

    标签: angularjs angularjs-validation


    【解决方案1】:

    如果您在 http 成功回调中可以访问范围,则可以这样做来设置有效性或将其标记为脏。

    scope.userForm.name.$setDirty();
    

    或

    scope.userForm.name.$setValidity('serverError', false); // creating a new field in $error and makes form field invalid.
    

    【讨论】:

      【解决方案2】:

      要设置表单的有效性或原始值,您必须使用 form.FormController 提供的函数。您可以将表单设置为原始或脏,但不能直接将表单设置为有效。您必须将特定模型设置为无效,这将触发表单值无效,这将触发表单无效 (https://docs.angularjs.org/api/ng/type/form.FormController)。

      //UserController
      //$scope.userName is your object which has it's own controller using Angular Forms.
      
      app.controller("UserController", function($scope){
       $http({
          method : 'POST',
          url : '/create',
          data : user,
          headers : {
            'Content-Type' : 'application/x-www-form-urlencoded'
          }
        })
        .success(function(data) {
          // I want to do something like this 
          $scope.userForm.$setDirty(); //Sets $pristine to false;  Alternatively, you could call $setPristine() to set $pristine to true
          $scope.userForm.name.$setValidity("length",false); //In your case, the "length" validation is likely something different or will be generic.  This enables you to have name fail validation based multiple rules (perhaps length and unique)
        });
      });
      

      【讨论】:

        【解决方案3】:

        如果要检查特定字段的有效性,可以使用自定义指令:

        app.directive('customValidation', function(dataService) {
            return {
                restrict: 'A',
                require: 'ngModel',
                link: function (scope, element, attrs, ctrl) {
                    ctrl.$parsers.unshift(function(viewValue){
                        //first, assume the value is valid, until proven otherwise
                        ctrl.$setValidity('customValidation', true);
        
                        //check against the API
                        if(viewValue.length > 0 && !ctrl.$error.customValidation) {
                            dataService.checkValidity(viewValue).then(function(response){
                                //API logic here
                                var results = response.data;
                                if(results.isNotValid)
                                    ctrl.$setValidity('customValidation', false);
                            }).catch(function(response){
                                //some error occurred
                                ctrl.$setValidity('customValidation', false);
                            });
                        }
                    });
                }
            };
        });
        

        使用它:

        <input custom-validation ng-model-options="{updateOn: 'default blur', debounce: { 'default': 700, 'blur': 0 }}" />
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-02-15
          • 1970-01-01
          • 2018-07-26
          • 1970-01-01
          • 2015-09-10
          • 2018-06-27
          • 1970-01-01
          相关资源
          最近更新 更多