New to AngularJS. Trying to figure out how I would accomplish this, or if it is possible at all.
I know I can bound a value to the input box by using
<input type="number" ng-model="myvalue">
But what if I want it such that the value between the model and the view is transformed?
For example, for currency, I like to store my value in cents. However, I want to allow my users to enter dollar amounts. So I need to convert the value by a factor of 100 between the view and controller, i.e. in the model I would have 100, and in the view, I would have 1.
Is that possible? If so, how can I achieve that?
I ran into the same problem as you. I started using wciu's solution but ran into an issue where the values would flicker between the cents and dollars. I ended up hooking into the pipeline that is used to do the binding between view and model.
merchantApp.directive('transformTest', function() {
return { restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
if(ngModel) { // Don't do anything unless we have a model
ngModel.$parsers.push(function (value) {
return value*100;
});
ngModel.$formatters.push(function (value) {
return value/100;
});
}
}
};
});
You could use the ngChange optional method on input elements to execute a function to manipulate the user input into the format that you are looking for on each change.
function Ctrl($scope) {
$scope.valueEntered = '';
$scope.value = '';
$scope.valueEnteredChanged = function () {
// more robust logic here
$scope.value = $scope.valueEntered * 100;
}
}
and with markup that looks like this.
<div ng-controller="Ctrl">
<input type="number" ng-model="valueEntered" ng-change="valueEnteredChanged()" /><br />
<span ng-bind="valueEntered"></span><br />
<span ng-bind="value"></span>
</div>
$watch the model/dollar value and keep a cents property in synch:
function MyCtrl($scope) {
$scope.$watch('dollars', function(dollars) {
$scope.cents = $scope.dollars * 100;
})
}
Markup:
<input type="number" ng-model="dollars">
<br>{{dollars}} {{cents}}
Found out how to do this with a directive using NgModelController from this page http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
Basically, the following directive would multiply/divid by 100 for an input field with transformTest as an attribute.
merchantApp.directive('transformTest', function() {
return { restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$render = function () {
element.val(ngModel.$viewValue / 100);
}
element.bind('blur keyup change', function() {
scope.$apply(read);
ngModel.$render();
});
read();
function read() {
ngModel.$setViewValue(element.val() * 100);
}
}
};
});
I would just use Object.defineProperty to solve this problem, for example:
var prop = 0;
Object.defineProperty($scope, "prop", {
get: function () {
return prop / 100;
},
set: function (value) {
prop = parseInt(value) * 100;
}
});
The variable prop is now always = $scope.prop * 100.