我有一个用于显示货币值的过滤器,它扩展了默认货币过滤器。我们的API将以美分存储数据,但我希望用户界面显示的价格类似于人们使用它的方式(美元和美分)。
过滤器是直接的,适用于普通字段,ui。网格等…
/**
* Currency Filter
*/
angular.module('myApp').filter('SLS_Currency', function($filter) {
var CurrencyFilter = $filter('currency');
return function(Input){
return CurrencyFilter(Input / 100);
};
});
将数字转换为美元和美分(123变成$1.23)。然而,我的问题是现在在输入字段的表单上使用它。我希望仍然能够控制错误检查等……,并希望该字段显示为$1.23,但在编辑时允许用户键入有或没有格式化的值?
我希望能够重用这个过滤器,不一定要创建另一段代码来做同样的事情。我已经看到了$watch的建议,但它似乎更大的形式会有一些这样的,然后会有一个指令输入,和一个过滤器查看。是否可以在过滤器内完成,或者在任何地方使用指令,包括ui.Grid?
<form>
<div class="form-group">
<label>Unit Price</label>
<input type="text" placeholder="Unit Price (cents)" ng-model="storeitem.UnitPrice | SLS_Currency" class="form-control" />
</div>
<div class="form-group">
<label>Quantity</label>
<input type="text" placeholder="Quantity (1-99)" ng-model="storeitem.nForQuantity" class="form-control" />
</div>
</form>
最好使用指令来完成此操作。如果你愿意,你可以在指令中使用你的过滤器。
angular.module('slsCurrency.directive', []).directive('slsCurrency',
function($filter) {
return {
restrict: 'A',
require: '^ngModel',
link: function($scope, element, attrs, ngModelController) {
var slsCurrencyFilter = $filter('SLS_Currency');
ngModel.$formatters.push(function(value){
return slsCurrencyFilter(value);
});
ngModel.$parsers.push(function(value){
// Insert code here to detect formatting (e.g. $), strip out what you don't need, then return it.
// This is the value that will be saved to your DB
return value;
});
}
};
}
);
<input type="text" sls-currency placeholder="Unit Price (cents)" ng-model="storeitem.UnitPrice" class="form-control" />