2017-03-23 11 views
0

私は損失または利益であるかどうかに応じて、$ 1.5金額で$ Money金額を赤または緑で書き込むよう指示を作成します。角度1.5 - お金の色を表示するカスタムディレクティブ

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

マイカスタムディレクティブは、これまでのところ、私は色の通貨で$マネーの量を書き出すんどのようにこのようになりますか?

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

何が欲しいですか? model.Moneyは通貨フォーマットになりますか? –

+0

はい、終了結果は

$55
のようになります。 –

答えて

1

あなたがコールバック関数にnewValueパラメータを確認することができ$watch使用。

希望の値を取得するには、currencyフィルタを使用して、必要なフォーマットに量を取得します。

値を設定するには、elementにAngularJSのjqLite htmlメソッドを使用して値を設定します。

HERESに実施例(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>

2

実装使用して、NG-クラス

指令:

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} 
関連する問題