范围复选框值未传递给指令?

时间:2014-06-11 04:14:06

标签: javascript regex angularjs validation

这是一个使用正则表达式进行简单验证的指令。出于某种原因,我在传递指令之外的复选框值时遇到问题。我试图在我的指令checkEmailOnBlur中读取名为scope.validationEnabled的复选框值:

app.directive('checkEmailOnBlur', function() {
  var ABN_REGX = /^(\d *?){3}$/;
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elm, attr, ctrl) {

      if (scope.validationEnabled) {

        if (attr.type === 'radio' || attr.type === 'checkbox') return;
        elm.unbind('input').unbind('keydown').unbind('change');

        elm.bind('blur', function() {
          scope.$apply(function() {
            if (ABN_REGX.test(elm.val())) {
              ctrl.$setValidity('abns', true);
              console.log('valid abn');
              scope.acn = "1010101";
              scope.displayName = "display name";
              scope.otherName = "otherName";
              scope.description = "desc";

            } else {
              ctrl.$setValidity('abns', false);
              console.log('not valid abn');
              scope.acn = "";
              scope.displayName = "";
              scope.otherName = "";
              scope.description = ""
            }
          });
        });
      }
    }
  };

问题:当我选中复选框时,for scope.validationEnabled目前未设置为TRUE。如何传递复选框值? 这是一个plnkr引用:http://plnkr.co/edit/O69SP2sB5NZcPirImhrh?p=preview

1 个答案:

答案 0 :(得分:0)

执行链接功能时,scope.validationEnabledundefinedfalsyblur。链接函数不会将事件侦听器附加到if

直到下次编译HTML时链接函数才会再次运行,因此如果选中该框,则无关紧要。

elm.bind('blur', function() { if (!scope.validationEnabled) return; // Code 移动到事件监听器函数中:

{{1}}

演示: http://plnkr.co/edit/qS5YP546qX8I9QwIwupz?p=preview