美元到美分和Angular JS

时间:2016-07-22 23:44:22

标签: javascript angularjs

我正在尝试输入一个美元金额(5.75)并将其转换为575并存储在数据库中,然后再次在网站上显示为5.75。

我的作品价格为5.00美元但不会以5.75美元的价格合作。我的内容如下。

HTML

<input type="number" class="form-control" ng-model="admin.singleInfo.pricing.cost" monetary-input ng-change="admin.calculateSell(admin.singleInfo.$id); admin.singleInfo.$save();changesSaved()"/>

FILTER

.filter('MonetaryUnit', function () { 
    return function (amount) {
        return (amount / 100).toFixed(2); 
    } 
})

指令

directive('monetaryInput', function($filter, $browser) {
    return {
        require: 'ngModel',
        link: function($scope, $element, $attra, ngModelCtrl) {
            var listener = function() {
                $element.val($filter('MonetaryUnit')(value, false));
            };

            ngModelCtrl.$parsers.push(function(viewValue) {
                return Math.round(parseInt(viewValue) * 100);
            });

            ngModelCtrl.$render = function() {
                $element.val($filter('MonetaryUnit')(ngModelCtrl.$viewValue, false));
            }

            $element.bind('change', listener);
        }
    }
})

1 个答案:

答案 0 :(得分:0)

很简单。只需将parseInt更改为parseFloat即可。请参阅下面的工作示例:

&#13;
&#13;
var app = angular.module("sa", []);

app.controller("FooController", function($scope) {

});

app.filter('MonetaryUnit', function() {
  return function(amount) {
    return (amount / 100).toFixed(2);
  }
});

app.directive('monetaryInput', function($filter, $browser) {
  return {
    require: 'ngModel',
    link: function($scope, $element, $attra, ngModelCtrl) {
      var listener = function() {
        $element.val($filter('MonetaryUnit')(value, false));
      };

      ngModelCtrl.$parsers.push(function(viewValue) {
        return Math.round(parseFloat(viewValue) * 100);
      });

      ngModelCtrl.$render = function() {
        $element.val($filter('MonetaryUnit')(ngModelCtrl.$viewValue, false));
      }

      $element.bind('change', listener);
    }
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="sa" ng-controller="FooController">
  <input type="text" ng-model="amount" monetary-input />

  <br>Model value: {{amount}}
</div>
&#13;
&#13;
&#13;