smoksnes smoksnes - 4 months ago 9
AngularJS Question

Display one value for user, but keep another in the model

I have a form where the user enters some numbers. These numbers are indexes. The problem is that when I'm posting the model to the server I need the index to be zero-based. But the index should be presented for the user as one-based.

So when the model has index 4, it should be presented to the user as 5.

Is it possible to do this? I rather not manually change it before posting, because it's actually several values, and not just one.



var myApp = angular.module('myApp',[]);


function MyCtrl($scope) {
$scope.model = {
index: 3
}

// Later I post the model with ajax.
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Enter index: <input type="number" ng-model="model.index"><br/><br/>

Actual index is <strong>{{model.index}}</strong> (Should be one less than what is shown in input)
</div>
</div>




Answer

You could make a directive to alter the value displayed to the user like this:

var myApp = angular.module('myApp',[]);


function MyCtrl($scope) {
    $scope.model = {
      index: 3
    }
    
    // Later I post the model with ajax.
}

myApp.directive('correctIndex', function()
{
    return{
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelController)
        {
            ngModelController.$formatters.push(function(value)
            {
                return value+1;
            })

            ngModelController.$parsers.push(function(value)
            {
                return value-1;
            })   
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    Enter index: <input correct-index type="number" ng-model="model.index"><br/><br/>
       
    Actual index is <strong>{{model.index}}</strong> (Should be one less than what is shown in input)
  </div>
</div>