2014-06-11 30 views
0

這是一個使用正則表達式進行簡單驗證的指令。出於某種原因,我有問題傳遞在指令外的複選框值。我想讀這是在我的指令稱爲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 = "" 
      } 
      }); 
     }); 
     } 
    } 
    }; 

問:此刻的scope.validationEnabled未設置爲TRUE,當我選中複選框。我如何傳遞複選框的值? 這裏是一個plnkr參考:http://plnkr.co/edit/O69SP2sB5NZcPirImhrh?p=preview

回答

0

當執行鏈接功能scope.validationEnabled將在這種情況下是undefined這是falsy。鏈接功能不會將事件監聽器附加到blur

直到下一次編譯HTML時,鏈接函數纔會再次運行,因此,如果選中該框,則無關緊要。

移動if到事件監聽功能:

elm.bind('blur', function() { 

    if (!scope.validationEnabled) return; 

    // Code 

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