我有许多从 API 返回的资源,需要将日期字符串转换为 Date 对象,以便它们可以由 md-datepicker(Angular Material)渲染。
起初,我只是在每个服务中执行此操作(事实上,我从每个服务调用另一个服务,将字符串转换为日期),但这变得很难维护。
因此,我尝试通过扩展 md-datepicker 指令来实现此目的,但我不知道如何修改该值 - 并且每次使用都会有不同的父 Controller 。
这是我得到的: app.js
.directive('customDatePicker', function(DatesService) {
return {
restrict: 'A',
require: 'mdDatepicker',
scope: {
date: '='
},
link: function(scope, element, attrs, controller, transcludeFn) {
// access value in scope here
console.log(scope);
}
}
})
编辑任务.html
<md-datepicker custom-date-picker date="TaskDetailCtrl.task.start_date" ng-model="TaskDetailCtrl.task.start_date">
</md-datepicker>
我认为通过使用隔离范围,我可以更轻松地获取值 - 并且使用哪个 Controller 并不重要(如果没有范围选项,我可以看到该值,但必须知道该值的名称) Controller )。
不幸的是,I get a Multiple Directive Resource Contention Error.
有更好的解决方案吗?
最佳答案
只需通过 attr 指令添加格式化程序
.directive('myDate', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElem, iAttrs, ngModelCtrl){
ngModelCtrl.$formatters.unshift(function(modelValue){
return modelValue && new Date(modelValue);
});
}
};
})
关于javascript - 在 md-datepicker 的渲染上将字符串转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39849462/