Search code examples
javascriptangularjsangularjs-directiveangularjs-model

Updating only the 'view' value using angular directive


So I have a decimal value in controller like this:

// Controller
var MyController = function($scope) {
    ...
    $scope.percentValue = 0.05; // can be stored
    ...
};

<!-- View -->
<span>{{percentValue}}</span>
<input ng-model="percentValue" />

With the above code, the value in the input element is 0.05 - however, I want to allow a user to enter an integer value like 5.

So if the $scope.percentValue is 0.05, I want to show it as 5 in the input element. And if a user enters 5, the $scope.percentValue should be 0.05.

However, the tricky thing here is I only want to update the view value - meaning that the span element should still show 0.05. Only the value in the input element should be 5.

I am trying to achieve this with ngModel, but I am still struggling.

This is what I have now:

var MyDirective = function() {
    function link(scope, element, attrs, ngModel) {
        ngModel.$render = function() {
            element.val(ngModel.$viewValue || '');
        };

        ngModel.$formatters.push(function (value) {
            return value * 100;
        });

        element.on('change blur', function() {
            ngModel.$setViewValue(element.val());
        }); 
    }

    return {
        restrict: 'A',
        require: '?ngModel',
        scope: {},
        link: link
    };
};

Please advise!!


Solution

  • Including my comment as an answer because it seemed to help. :-)

    To summarise: since you've already provided a $formatters function for your directive, which converts a model value ($modelValue) to displayed form ($viewValue), it's simply a matter of providing a $parsers function to do the reverse and convert any user input back to the model value.

    Example Plunker