AngularJS - 格式化模板之前,NG-模式自定义指令呈现 [英] AngularJS - Formatting ng-model before template is rendered in custom directive
问题描述
我创造的角度JS自定义指令。我想模板呈现前格式化NG-模式。
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>
我想在模板的ngModel进入前对其进行格式化unformattedDate值。事情是这样的:
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
暴露了其控制器<一个href=\"http://docs.angularjs.org/api/ng.directive%3angModel.NgModelController\"><$c$c>ngModelController$c$c> API 并为您提供一种方式来做到这一点。
ngModel
exposes its controller ngModelController
API and offers you a way to do so.
在你的指令,你可以添加<一个href=\"http://docs.angularjs.org/api/ng.directive%3angModel.NgModelController#%24formatters\"><$c$c>$formatters$c$c>该做的正是你需要什么,<一个href=\"http://docs.angularjs.org/api/ng.directive%3angModel.NgModelController#%24parsers\"><$c$c>$parsers$c$c>,那些周围的其他方法(解析价值不言而喻模型前)。
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-模式自定义指令呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!