2015-05-26 52 views
0

我試圖使用輸入掩碼jQuery plugin作爲指令,但在Chrome的控制檯錯誤中出現以下錯誤。將jQuery插件轉換爲AngularJS指令

TypeError: Cannot read property 'length' of undefined 

我的代碼

JS

var app = angular.module('app', ['ngResource']); 

app.directive('inputMask', function(){ 
    return { 
     restrict: 'A', 
     link: function(scope, element){ 
      element.mask(); 
     } 
    } 
}) 

HTML

<input type="text" class="form-control input-mask" data-input-mask data-mask="{mask: 00/00/0000}" placeholder="eg: 23/05/2014"> 

http://plnkr.co/edit/Kp3SYS0cbIfVm1gTwtE0?p=preview

請幫我解決這個問題。

+0

使用已經創建的指令,而不是創建自己的http://angular-ui.github.io/ui-utils/ –

回答

1

長度錯誤是因爲element.mask()方法需要一個帶有要使用的掩碼字符串的屬性。 (在這種情況下'00/00/0000')。 所以,你必須改變一些事情,首先你的指令:

var app = angular.module('app', ['ngResource']); 

app.directive('inputMask', function(){ 
    return { 
     restrict: 'A', 
     scope: { 
      inputMask: '=' 
     }, 
     link: function(scope, element){ 
      element.mask(scope.inputMask.mask); 
     } 
    } 
}) 

然後在HTML,所以你可以設置元素中的面具。

<input type="text" class="form-control" data-input-mask="{mask: '00/00/0000'}" placeholder="eg: 23/05/2014"> 

這裏是一個Plunker工作:

http://plnkr.co/edit/BbJtsF9mWx4n29CfZajF?p=preview

+0

這太酷謝謝。我認爲,無論何時插件需要來自數據屬性的東西,我都需要以這種方式處理。非常感謝你的回答和簡單的解釋。愛你... – Body