我正在尝试输入一个美元金额(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);
}
}
})
答案 0 :(得分:0)
很简单。只需将parseInt
更改为parseFloat
即可。请参阅下面的工作示例:
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;