如何在同一个元素上使用$ parsers和$ validators执行两个不同的指令?

时间:2016-06-23 17:31:45

标签: angularjs validation parsing angularjs-directive

问题是只有第一个指令正在运行而另一个指令不正常。以下是两个指令。单独工作时两者都可以正常工作。

  .directive("restrictInvalidInput", function($rootScope, utils) {
      return {
          restrict: "A",
          require: "ngModel",
          priority: 1,
          link: function(scope, elem, attr, ctrl) {
              var remove_invalid_chars = function() {
                  //blah blah
              };

              ctrl.$parsers.push(remove_invalid_chars);
          }
      }
  })

  .directive("validateUsername", function($rootScope, utils) {
      return {
          restrict: "A",
          require: "ngModel",
          priority: 2,
          link: function(scope, elem, attr, ctrl) {

              var validate_username = function(modelValue, viewValue) {
                  //blah blah
              };

              ctrl.$validators.valid_username = validate_username;
          }
      }
  });

1 个答案:

答案 0 :(得分:1)

似乎问题出在[1, 2, 3]的位置。您确定,该解析器返回一个值吗?因为(from docs):

  

从解析器返回blah blah表示发生了解析错误。在这种情况下,不会运行undefined

WORKING PLUNKER



$validators

angular.module('app', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.name = 'Some name';
  }])
  .directive("restrictInvalidInput", function() {
    return {
        restrict: "A",
        require: "ngModel",
        priority: 1,
        link: function(scope, elem, attr, ctrl) {
            var remove_invalid_chars = function(viewValue) {
                console.log('Look, I\'m parsing');
                return viewValue;
            };

            ctrl.$parsers.push(remove_invalid_chars);
        }
    }
})
.directive("validateUsername", function() {
    return {
        restrict: "A",
        require: "ngModel",
        priority: 2,
        link: function(scope, elem, attr, ctrl) {
            var validate_username = function(modelValue, viewValue) {
                console.log('Look, I\'m validating');
                return true;
            };

            ctrl.$validators.valid_username = validate_username;
        }
    }
});