Search code examples
javascriptangularjsangular-ngmodelangularjs-ng-model

ng-model manipulating value when typing and displaying


I have the following variable:

$scope.pixelWidth = "30px";

And I have an input box like so:

<input ng-model="pixelWidth" />

I'd like for the input box to only have the numbers inside it but still insert the px into $scope.pixelWidth while typing.

Is there a way to accomplish this?


Solution

  • Yes, you need to create a directive and add formatters and parsers to the ngModelController. See working version on plunker

    Directive:

    app.directive('modelSuffix', [function() {
      return {
        restrict: 'AE',
        require: '^ngModel',
        link: function(scope, element, attributes, ngModelController) {
              var suffix = attributes.modelSuffix;
              // Pipeline of functions called to read value from DOM 
              ngModelController.$parsers.push(function(value) {
                return value + suffix;
              });
    
              // Pipeline of functions called to display on DOM
              ngModelController.$formatters.push(function(value) {
                return value.replace(suffix, '');
              });
            }
      }
    }]);
    

    And use it like so:

    <input ng-model="pixelWidth" model-suffix="px"/>