如何手动更改输入标签的$error值 - Angularjs.



我正在通过角度$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函数中的事情。因此,它将显示错误消息。

如果您有权访问 http 成功回调中的范围,则可以执行此操作以设置有效性或将其标记为脏。

scope.userForm.name.$setDirty();

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

若要设置表单的有效性或原始值,必须使用表单提供的函数。表单控制器。 您可以将表单设置为原始或脏,但不能将表单直接设置为有效或不正常。 您必须将特定模型设置为无效,这将触发表单值无效,这将触发表单无效 (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)
  });
});

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

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 }}" />

最新更新