AngularJS指令范围属性匹配

时间:2014-09-18 20:59:26

标签: javascript angularjs angularjs-directive

我正在尝试编写一个隔离指令,它将运行正则表达式来验证某些输入字段。 我希望该指令知道要匹配的正则表达式并根据输入的属性使用。

示例输入看起来像这样。

<input required tabindex="5" regex-validation regex="validationRegex.zipRegex" ng-model="payment.zip" type="text" />
下面的

是指令中的一个示例,它设置一个控制器以匹配指令本身。 scope.regex.test记录未定义。

module.controller('Controller', function($scope) {
    $scope.validationRegex = {
        americanExpressRegex: new RegExp(/^(?!3[47]).*$/),
        cvvRegex: new RegExp(/^[0-9]{3,4}$/),
        currencyRegex: new RegExp(/^[$]?\d{0,18}\.?\d{0,2}$/),
        cityRegex: new RegExp(/^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$/),
        zipRegex: new RegExp(/^[0-9]{5}(?:-[0-9]{4})?$/),
        phoneRegex: new RegExp(/^(\d(\s|\.|\-)?)?\(?\d{3}\)?(\s|\.|\-)?\d{3}(\s|\.|\-)?\d{4}$/),
        /* jshint ignore:start */
        emailRegex: new RegExp("^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$"),
        /* jshint ignore:end */
        numberRegex: new RegExp(/^\d+$/),
        addressRegex: new RegExp(/^[A-Za-z0-9 \-_\.,]{0,55}$/),
        bankAccountRegex: new RegExp(/^[0-9]{1,17}$/),
        routingNumberRegex: new RegExp(/^((0[0-9])|(1[0-2])|(2[1-9])|(3[0-2])|(6[1-9])|(7[0-2])|80)([0-9]{7})$/)
    };
})
    .directive('regexValidation', [function () {
        return {
        scope: { regex: "=" },
        link: function (scope, element) {
            element.bind('change', function () {
                console.log(scope.regex);
                //grab the element we are working with into a jquery element
                var ele = $(element);

                //grab the element value for multiple future use
                var value = ele.val();

                //if we have a value check with regex
                if (value && !**scope.regex.test**(value)) {
                    ele.parent().addClass("error");
                }
                    //this will set the element back to how it was and check to see if all validation is
                    //complete
                else {
                    ele.parent().removeClass("error");
                }
            });
        }
    };
}]);

2 个答案:

答案 0 :(得分:2)

摆脱jQuery,永远不要回头。你将使用Angular进一步做到这一点。

Angular已经在处理输入值的变化并通过管道运行它。您需要使用该管道与值进行交互,而不是附加事件侦听器。

查看ngModelController documentation here.

我在很多more detail and with a demo here.

中解释了这个过程

如果您使用的是最新版本的Angular,那么您将使用$validator。对于旧版本,您可以使用$parser。使用ngModel的$ error状态,而不是添加一个类来声明状态。这是一个让你入门的例子。

Live demo

.controller('myCtrl', function($scope) {

  $scope.foo = 'abc';
  // in my example, it's always going to be invalid
  $scope.fooValidity = false;

})

.directive('myDirective', function() {

  var directive = {
    scope: {
      isValid: '=myDirective'
    },
    require: 'ngModel',
    link: function($scope, $element, $attrs, $ngModel) {

      // "whatever" is the property which will be assinged on the ngModel $error object
      $ngModel.$validators.whatever = function(val) {
        // write your validation logic here
        // return true or false for valid / invalid
        return $scope.isValid;
      };

    }
  };

  return directive;

})

;

标记:

<!-- Add the `error` class by using the model's error object -->
<!-- Also note that Anuglar will add a `ng-invalid-whatever` class for you -->
<form name="myForm" ng-class="{error:myForm.fooInput.$error.whatever}">
  <input ng-model="foo" name="fooInput" my-directive="fooValidity">
  <p ng-show="myForm.fooInput.$error.whatever">It's invalid!</p>
</form>

答案 1 :(得分:-1)

混合Angularjs和jQuery不是最好的选择。但是你可以在没有jQuery的情况下验证你的输入,在http://plnkr.co/edit/UzQ6DZcKYLk3PCHeEJiv?p=preview

看到我的工作演示

只需将模型和正则表达式传递给指令,然后在模型更新

上测试正则表达式
app.directive('regexValidation', [

  function() {
    return {
      scope: {
        regex: "=",
        model: '=ngModel'
      },
      link: function(scope, element, attr) {
        scope.$watch('model', function(newValue, oldValue) {


          if (!newValue|| scope.regex.test(newValue)) {
            element.removeClass("error").addClass('valid');
          } else {
            element.addClass("error").removeClass('valid');
          }
        });
      }
    };
  }
]);
相关问题