Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with two directives on the same model

I wrote two directives. One of them is used for entering numbers with units (like "1m"):

angular.module('ng', [])
.directive('unit', function() {
    return {
        require: 'ngModel',
        link: function (s, e, attributes, ngModel) {
            ngModel.$parsers.push(function (i) {
                return i + attributes.unit;
            });

            ngModel.$formatters.push(function (i) {
                return (i + '').replace(attributes.unit, '');
            });
        }
    }
});

The second one replaces , with ., because many people in Europe use a decimal comma instead of a decimal point and I want my values to be normalized.

angular.module('ng', [])
.directive('numberWithPoint', function() {
    return {
        require: 'ngModel',
        link: function (s, e, attributes, ngModel) {
            ngModel.$parsers.push(function (i) {
                return i.replace(',', '.');
            });
        }
    }
});

The usage would be:

 <input type="text" ng-model="howLongSomethingIs" unit="m" number-with-point /> m

The issue: the directive unit works great if it is alone, if I add the number-with-point directive, the unit takes no effect (the displayed value is for example 1m not 1.

I tried messing up with the priority property within the return object, but nothing happened.

How to make these two directives work together?

In this jsfiddle, it seems to work, but it uses Angular 1.2.1. I am using Angular 1.3.14. Does somebody know how to make jsfiddle use other version?

like image 819
Liglo App Avatar asked Jul 11 '15 19:07

Liglo App


1 Answers

In this jsfiddle, it seems to work, but it uses Angular 1.2.1. I am using Angular 1.3.14. Does somebody know how to make jsfiddle use other version?

I just ran the supplied code locally on Angular 1.3.15 - worked just fine.

Inputting 123071823,1238 evaluates to 123071823.1238m when bound to the view. So it appears to be working just fine (on my end, and in your fiddle).

1.3.14 jsFiddle


Loading a different version on jsFiddle:

  1. Remove angular from the `Frameworks & Extensions tab
  2. Grab your version from code.angularjs.org.
  3. Paste the link as an External resource in jsFiddle.
like image 105
Kasper Lewau Avatar answered Sep 19 '22 23:09

Kasper Lewau