简体   繁体   English

Angular JS:值更改时更新指令

[英]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: 基本上,您需要添加一个link函数来监视模型并应用所有更新:

https://jsfiddle.net/5d7ta5rb/ https://jsfiddle.net/5d7ta5rb/

HTML 的HTML

<div ng-app="myModule" ng-controller="cont">
  <input ng-model="myMoney" type="number">
  <money ng-model="myMoney"></money>
</div>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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