Brayan Brayan - 4 months ago 20
AngularJS Question

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/

Answer

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