AngularJS - 在自定义指令中呈现模板之前格式化 ng-model [英] AngularJS - Formatting ng-model before template is rendered in custom directive
问题描述
我正在 Angular JS 中创建自定义指令.我想在模板呈现之前格式化 ng-model.
I am creating a custom directive in Angular JS. And I want to format the ng-model before the template renders.
这是我目前所拥有的:
app.js
app.directive('editInPlace', function() {
return {
require: 'ngModel',
restrict: 'E',
scope: { ngModel: '=' },
template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
};
});
html
<edit-in-place ng-model="unformattedDate"></edit-in-place>
我想在将 unformattedDate 值输入到模板的 ngModel 之前对其进行格式化.像这样:
I want to format the unformattedDate value before it is entered in the ngModel of the template. Something like this:
template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'
但这给了我一个错误.如何做到这一点?
but that gives me an error. How to do this?
推荐答案
ngModel
公开其控制器 ngModelController
API 并为您提供了一种方法.
ngModel
exposes its controller ngModelController
API and offers you a way to do so.
在您的指令中,您可以添加 $formatters
完全满足您的需求,$parsers
,反之(在值进入模型之前对其进行解析).
In your directive, you can add $formatters
that do exactly what you need and $parsers
, that do the other way around (parse the value before it goes to the model).
你应该这样做:
app.directive('editInPlace', function($filter) {
var dateFilter = $filter('dateFormat');
return {
require: 'ngModel',
restrict: 'E',
scope: { ngModel: '=' },
link: function(scope, element, attr, ngModelController) {
ngModelController.$formatters.unshift(function(valueFromModel) {
// what you return here will be passed to the text field
return dateFilter(valueFromModel);
});
ngModelController.$parsers.push(function(valueFromInput) {
// put the inverse logic, to transform formatted data into model data
// what you return here, will be stored in the $scope
return ...;
});
},
template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
};
});
这篇关于AngularJS - 在自定义指令中呈现模板之前格式化 ng-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!