How to manipulate view value without affecting original variable in AngularJS
I wanted to change the value of the ng model view in angularjs without affecting the underlying model variable. I have defined the scope variable markPercent in my controller.
$scope.markPercent = 0.43;
And I am trying to access the same from my view using ng-model.
<input type="text" ng-model="markPercent">
This input displays 0.43 in html view. And what I wanted was 43 in the html view, without affecting the $ scope.markPercent value . Also if the user changes the value in the input field that should change the scope variable accordingly (for example: if the user enters 65 then $ scope.markPercent should be 0.65). I don't really want to multiply and divide by 100 each and every time inside the clock (this is how I do it now). How do we do this in angular?
source to share
This applies to pipelines ngModel.$parsers
/ ngModel.$formatters
( ref ). You will need a directive that will require
ngModel
put your own code into these two pipelines. For example:.
app.directive("percent", function() {
/** Convert a string view value to percent float from 0.0 to 1.0. */
function parser(value) {
// implement this
}
/** Convert a float from 0.0 to 1.0 to percent. */
function formatter(value) {
// implement this
}
return {
restrict: "A",
require: "ngModel",
link: function(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(parser);
ngModel.$formatters.push(formatter);
}
};
});
Working example with simplified parser / formatting: http://jsfiddle.net/748j30ha/
source to share