Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to transform a value between view and model in AngularJS for input?

Tags:

angularjs

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?

like image 516
wciu Avatar asked Nov 16 '12 16:11

wciu


People also ask

Can we use NG model for Div?

NgModel expects the bound element to have a value property, which div s don't have. That's why you get the No value accessor error. I don't know if the input event is supported on all browsers for contenteditable . You could always bind to some keyboard event instead.

What does * ngIf mean?

A shorthand form of the directive, *ngIf="condition" , is generally used, provided as an attribute of the anchor element for the inserted template. Angular expands this into a more explicit version, in which the anchor element is contained in an <ng-template> element.

What is data ng model in AngularJS?

ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form. We can use ngModel with: input.

Which method is used to create models in AngularJS?

In basic examples, AngularJS uses the $scope object as the model. However, in the previous article I showed how using the controllerAs method allowed the controller itself to be added to the scope with a given name and essentially be used as the model.


1 Answers

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;         });        }     }   }; }); 
like image 200
gingermusketeer Avatar answered Oct 05 '22 23:10

gingermusketeer