BahaiResearch.com BahaiResearch.com -4 years ago 220
AngularJS Question

Angular 1.5 - Custom directive to show Money Color

I'm creating a directive in Angular 1.5.x to write the $Money amount in red or green, depending on if it's a loss or profit.

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


My custom directive looks like this so far, how do I write out the $Money amount in Currency with the color?

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

Answer Source

Using $watch you can check the newValue parameter in the callback function.

To get your desired value, use the currency filter to get the amount into the format you need.

To set the value you can use AngularJS's jqLite html method on the element to set the value.

Heres a working example (the amount value changes after 5 seconds to demonstrate the negative amount):

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download