0

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}}

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Does this work the same for version 1.2.x? Because I seem to be getting a syntax error using this.
You need to change your assignment from {{value}} to just value in your html view
0

Why don't you use built-in filters? https://docs.angularjs.org/api/ng/filter/number

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.