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?
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.
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.
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.
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.
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; }); } } }; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With