我将模板中的日期元素附加为
<input type="date" ng-model="experience.date_start" date-ob>
ng-model将绑定值作为日期的字符串。为此,我需要将此字符串转换为对象(新日期(experience.date_start))。我试图通过名为 date-ob
的指令来实现此上下文.directive('dateOb', function(){
return {
require: 'ngModel',
scope: {},
link: function(scope, element, attrs, ctrl) {
ctrl.$parsers.push(function(value) {
console.log('parser!', value);
return new Date(value);
});
ctrl.$formatters.push(function(value) {
console.log('formatter!', value);
return value;
});
}
}
});
它抛出
错误:[ngModel:datefmt]预期
2014-08-28
为日期 http://errors.angularjs.org/1.4.5/ngModel/datefmt?p0=2014-08-28
如何使用date-ob指令中的代码呢? 我是新手到.directive请给我解释说明???? ..
答案 0 :(得分:2)
看看formatters and parsers - 它们用于这些事情。解析器更改视图中的值将如何存储在模型中。格式化程序会更改模型中的值在视图中的显示方式。
使用指令你可以这样做:
angular.module('myApp', [])
.directive('wrapperDirective', function(){
return {
link: function(scope) {
scope.experience = {date_start: '2015-01-01'};
}
};
})
.directive('dateOb', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
// view --> model (change date to string)
ngModel.$parsers.push(function(viewValue){
return viewValue.toISOString();
});
// model --> view (change string to date)
ngModel.$formatters.push(function(modelValue){
return new Date(modelValue);
});
}
};
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="myApp" wrapper-directive>
<p>Date is: {{experience.date_start}}</p>
<input type="date" ng-model="experience.date_start" date-ob>
</div>
&#13;
答案 1 :(得分:1)
.directive('dateOb', function(){
return {
scope: {
dateModel :'=ngModel'
},
link: function(scope, element, attrs, ctrl) {
scope.$watch('dateModel',function(n,o){
if(!n instanceOf Date)
{
scope.dateModel = new Date(dateModel);
}
});
}
}
});