简体   繁体   中英

Angular JS: Update a directive when the value changes

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?

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];
        }
      });
    }
  }
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM