【问题标题】:Cannot pass array to angular directive无法将数组传递给角度指令
【发布时间】:2016-02-05 15:04:24
【问题描述】:

无法将数组传递给 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'}" />

【问题讨论】:

  • 问题可能是单引号。
  • '@' 属性告诉指令需要一个字符串,因此您可以将一个字符串传递给它,然后将其操作到一个数组中,该数组在链接函数中指令可以理解。不过,您在 input-mask 属性中显示的内容看起来不像一个数组。

标签: javascript angularjs angularjs-scope directive input-mask


【解决方案1】:

属性值将返回一个字符串,而不是传递给插件所需的对象

您可以切换引号,以便字符串是有效的 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);
        }
    };
})

但实际上,如果不将字符串放在 html 中并将对象引用从控制器传递到隔离范围,这会简单得多

【讨论】:

    【解决方案2】:

    只需使用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'}" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2016-06-15
      • 2015-06-10
      • 2018-09-03
      • 1970-01-01
      相关资源
      最近更新 更多