Reputation: 365
I have the following directive that helps me to split the decimals from a number and present it with different styles in my view. Thing is, it does not update when the value changes.
I use this directive many many times to present in the view currencies related to money.
This is the directive:
app.directive('money', function(){
return {
restrict: 'E'
, scope: {
money: '@'
}
, controller: controller
, controllerAs: 'dvm'
, bindToController: true
, template: '<h2><sup>$</sup>{{ dvm.dollar }}<sub>.{{ dvm.cents }}</sub></h2>'
};
function controller(){
var parts = parseFloat(this.money).toFixed(2).split(/\./);
this.dollar = parts[0];
this.cents = parts[1];
}
});
I update the values several times depending on the user options, so these values are re-calculated every time the user picks options.
Currently, none of those values are updated when they are re-calculated. What is the better way to solve this?
Upvotes: 0
Views: 227
Reputation: 17466
Basically, you need to add a link
function that watches over your model and applies any updates:
https://jsfiddle.net/5d7ta5rb/
HTML
<div ng-app="myModule" ng-controller="cont">
<input ng-model="myMoney" type="number">
<money ng-model="myMoney"></money>
</div>
JavaScript
var app = angular.module('myModule', [])
app.controller('cont', function($scope) {
$scope.myMoney = 0;
})
app.directive('money', function() {
return {
restrict: 'E',
scope: {
ngModel: '=' //bi-directional binding
},
template: '<h2><sup>$</sup>{{dollars}}<sub>.{{cents}}</sub></h2>',
link: function(scope) {
scope.dollars = 0;
scope.cents = 0;
scope.$watch('ngModel', function(newval) {
if (newval) {
var parts = parseFloat(scope.ngModel).toFixed(2).split(/\./);
scope.dollars = parts[0];
scope.cents = parts[1];
}
});
}
}
});
Upvotes: 1