2016-02-05 49 views
0

无法将数组传递给Angular中的输入掩码插件。 也许有人可以帮助我。无法将数组传递给角度指令

angular.module('myproject.directives'). 
directive('inputMask', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      inputMask: '@' 
     }, 
     link: function(scope, el, attrs) { 
      $(el).inputmask(attrs.inputMask); 
     } 
    }; 
}); 

<input type="text" input-mask="{'mask': '9{4} 9{4} 9{4} 9{4}[9]', 'autoUnmask': 'true'}" /> 
+0

问题可能是单引号。 – Jai

+0

'@'属性告诉指令期望一个字符串,所以你可以将它传递给一个字符串,然后将它处理成一个数组,该指令可以在链接函数中理解。不过,您在input-mask属性中显示的内容看起来不像数组。 –

回答

0

因为需要传递给插件

可以围绕切换引号,这样的字符串是有效的JSON,然后解析JSON方式的属性值将返回一个字符串,而不是一个对象反对

<input type="text" input-mask='{"mask": "9{4} 9{4} 9{4} 9{4}[9]", "autoUnmask": "true"}' /> 

JS

.directive('inputMask', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      inputMask: '@' 
     }, 
     link: function(scope, el, attrs) { 
      var mask =JSON.parse(attrs.inputMask); 
      $(el).inputmask(mask); 
     } 
    }; 
}) 

但实际上这将b Ë简单得多不把HTML中的字符串,并从你的控制器传递一个对象引用到隔离范围,而不是

0

只需使用scope.$eval方法inputMask属性来执行表达式:

angular.module('myproject.directives') 
.directive('inputMask', function() { 
    return { 
     restrict: 'A', 
     scope: { 
      inputMask: '@' 
     }, 
     link: function(scope, el, attrs) { 
      $(el).inputmask(scope.$eval(attrs.inputMask)); 
     } 
    }; 
}); 

<input type="text" input-mask="{'mask': '9{4} 9{4} 9{4} 9{4}[9]', 'autoUnmask': 'true'}" />