Lul*_*ulu 11 templates model directive angularjs
我正在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>'
};
});
Run Code Online (Sandbox Code Playgroud)
HTML
<edit-in-place ng-model="unformattedDate"></edit-in-place>
Run Code Online (Sandbox Code Playgroud)
我想在将unformattedDate值输入模板的ngModel之前格式化.像这样的东西:
template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误.这该怎么做?
Cai*_*nha 25
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>'
};
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10264 次 |
最近记录: |