我正在用Angular JS创建一个自定义指令。并且我想在模板呈现之前格式化ng-model。
这就是我到目前为止所知道的:
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之前对其进行格式化。如下所示:
template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'但这给了我一个错误。该怎么做呢?
发布于 2013-04-09 20:44:41
ngModel公开了它的控制器ngModelController API,并为您提供了这样做的方法。
在您的指令中,您可以添加$formatters和$parsers,后者执行相反的操作(在值进入模型之前对其进行解析)。
下面是你应该怎么做:
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>'
};
});https://stackoverflow.com/questions/15901889
复制相似问题