【问题标题】:scope checkbox value not passed on to directive?范围复选框值未传递给指令?
【发布时间】:2014-06-11 04:14:06
【问题描述】:

这是一个使用正则表达式进行简单验证的指令。出于某种原因,我在传递指令之外的复选框值时遇到问题。我正在尝试在名为 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

【问题讨论】:

    标签: javascript regex angularjs validation


    【解决方案1】:

    当链接函数被执行时,scope.validationEnabled 在这种情况下将是undefined,即falsy。链接函数不会将事件监听器附加到blur

    直到下一次编译 HTML 时,链接函数才会再次运行,所以选中该框无关紧要。

    if移动到事件监听函数中:

    elm.bind('blur', function() {
    
      if (!scope.validationEnabled) return;
    
      // Code
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多