I've got a requirement such that for certain type of scope variables, I want to keep two decimal places in AngularJs. For this I've done the following:
html
<span floatval="{{someVariable}}">{{someVariable}}</span>
js
var app = angular.module('app',[]).directive('floatval', function(){
return function(scope, element, attrs){
var newInt = parseFloat(attrs.floatval);
var n = newInt.toFixed(2);
}
});
I'm stuck here as I dont know how to now reflect this new value in the place of the original scope {{somevariable}}
You can specify the scope of your directive. This way two-way binding is setup.
var app = angular.module('app',[]).directive('floatval', function(){
return {
scope: {
floatval: '='
},
link: function(scope, element, attrs){
scope.floatval = parseFloat(scope.floatval).toFixed(2);
}
};
});
Then you need to change your HTML <span floatval="someVariable">{{someVariable}}</span>
See https://code.angularjs.org/1.3.15/docs/guide/directive
Link to an example plnkr : http://plnkr.co/edit/aRyp1v9tGH7z8X28fewP?p=preview
Why don't you use built-in filters? https://docs.angularjs.org/api/ng/filter/number
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.