简体   繁体   English

多个元素的Angular指令

[英]Angular directive for multiple elements

I created this number format directive, but if I use it on more than one input, it doesn't work for all of them, but with only one it works. 我创建了这个数字格式指令,但如果我在多个输入上使用它,它不适用于所有这些,但只有一个它可以工作。 Any ideas? 有任何想法吗?

directive('formatUsNumber', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        priority: 100,
        link: function(scope, element, attrs, ngModel) {

            scope.formatNumber = function() {
                var n = element.val();
                var dest = n;
                if (n.length >= 10) {
                    if (/^[A-Za-z\s]+$/.test(n)) {
                        return;
                    }
                    dest = n.replace(/\D/g, '');
                    if (!isNaN(dest)) {
                        n = dest;
                    }
                    if (n.substr(0, 1) != "1") {
                        n = "1" + n;
                    }
                }
                element.val(n);
                ngModel.$setViewValue(n);
            };
        },
    };
});

The template: 模板:

<input type="text" ng-change="formatNumber()" format-us-number ng-model="myModel" />

Fiddle: http://jsfiddle.net/Lvc0u55v/7479/ 小提琴: http//jsfiddle.net/Lvc0u55v/7479/

Try adding an isolated scope, something like this: 尝试添加一个孤立的范围,如下所示:

restrict: 'A',
require: 'ngModel',
priority: 100,
scope:{
    ngModel:'='
},...

I think it's because scope of directive is not isolated. 我认为这是因为指令的范围不是孤立的。 And also I've made few changes, hope it workes the same 而且我也做了一些改变,希望它的工作原理相同

directive('formatUsNumber', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    priority: 100,
            scope: true,
    link: function(scope, element, attrs, ngModel) {

        scope.formatNumber = function() {
            var n = ngModel.$modelValue;
            if (n.length >= 10) {
                if (/^[A-Za-z\s]+$/.test(n)) {
                    return;
                }
                n = n.replace(/\D/g, '');
                if (!isNaN(dest)) {
                    n = dest;
                }
                if (n.substr(0, 1) != "1") {
                    n = "1" + n;
                }

                ngModel.$setViewValue(n, 'change:directive');
            }
        };
    },
  };
});

U can test it here 你可以在这里测试一下

For this use case I think that fits better implements a custom filter instead a directive. 对于这个用例,我认为更适合实现自定义过滤器而不是指令。 Building Custom AngularJS Filters Other alternative could be incude a custom parser and/or formatter. 构建自定义AngularJS过滤器其他替代方法可能包括自定义解析器和/或格式化程序。 AngularJS - Formatters and Parsers AngularJS - 格式化程序和解析器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM