javascript – 如何在角度中显示ng-model输入值作为货币?

前端之家收集整理的这篇文章主要介绍了javascript – 如何在角度中显示ng-model输入值作为货币?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有html
  1. <input type="text" ng-model="price" >
  2.  
  3. <h2>{{ price | currency}}</h2>

在控制器中

  1. $scope.price = 10;
  2. Which displays **$10** in h1 if i change the value in price model input.

我希望文本框输入为货币(输入框中的$10作为值).
怎么做到这一点?

解决方法

您可以尝试使用 formattersparsers之类的
  1. app.directive('currency',function () {
  2. return {
  3. require: 'ngModel',link: function(elem,$scope,attrs,ngModel){
  4. ngModel.$formatters.push(function(val){
  5. return '$' + val
  6. });
  7. ngModel.$parsers.push(function(val){
  8. return val.replace(/^\$/,'')
  9. });
  10. }
  11. }
  12. })

然后

  1. <input type="text" ng-model="price" currency>

演示:Fiddle

猜你在找的JavaScript相关文章