Angular 1.5 - 显示货币颜色的自定义指令

Angular 1.5 - Custom directive to show Money Color

我正在 Angular 1.5.x 中创建一个指令,根据它是亏损还是盈利,将 $Money 金额写成红色或绿色。

<div  financial-Color amount="model.Money"></div>

到目前为止,我的自定义指令看起来像这样,我如何用颜色写出货币中的 $Money 金额?

app.directive('financialColor', function () {
    return {
        restrict: 'EA',
        scope: {
            'amount': '='
        },

        link: function (scope, element, attrs) {
            scope.$watch('amount', function (condition) {
                if (attrs.amount<0) {
                    element.css('color', 'red');
                }
                if (attrs.amount > 0) {
                    element.css('color', 'green');
                };
            });
        }
    }

使用$watch你可以检查回调函数中的newValue参数。

要获得所需的值,请使用 currency 过滤器将金额转换为您需要的格式。

要设置值,您可以在 element 上使用 AngularJS 的 jqLite html 方法来设置值。

这是一个工作示例(数量值在 5 秒后发生变化以证明负数量):

// app.js
(function() {

  'use strict';

  angular.module('app', []);

})();

// main.controller.js
(function() {

  'use strict';

  angular.module('app').controller('MainController', MainController);

  MainController.$inject = ['$timeout'];

  function MainController($timeout) {

    var vm = this;

    vm.amount = 100.05;

    $timeout(function() {

      vm.amount = -55.10;

    }, 5000);

  }

})();

// financial-color.filter.js
(function() {

  'use strict';

  angular.module('app').directive('financialColor', financialColor);

  financialColor.$inject = ['$filter'];

  function financialColor($filter) {

    return {
      restrict: 'EA',
      scope: {
        'amount': '='
      },
      link: function(scope, element, attrs) {

        scope.$watch('amount', function(newValue, oldValue) {

          // set the value using the currency filter
          element.html($filter('currency')(newValue, '$', 2));

          if (newValue < 0) {

            element.css('color', 'red');

          } else if (newValue > 0) {

            element.css('color', 'green');

          }

        });
      }
    }
  }

})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

<div ng-app="app" ng-controller="MainController as MainCtrl">

  <div financial-color amount="MainCtrl.amount"></div>

</div>

使用 ng-class

实现

指令:

app.directive('financialColor', function () {
    return {
        restrict: 'EA',
        scope: {
            'amount': '='
        },
        template: "<span ng-class=\"{'red':amount<0, 'green': amount>0}\">${{amount}}</span>"
    }
});

CSS

.red {color: red}
.green {color: green}