如何使用 angularjs 指令过滤 ng-model 值?

how to filter the ng-model value using angularjs directive?

我将模板中的日期元素附加为

<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;
        });
    }       
}
});

它抛出

Error: [ngModel:datefmt] Expected 2014-08-28 to be a date http://errors.angularjs.org/1.4.5/ngModel/datefmt?p0=2014-08-28

date-ob指令中的代码应该怎么写呢? 我是 .directive 的新手,请给我解释的解决方案????..

看看 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);
      });
    }
  };
});
<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>

你可以做到。它解决了我的问题。

.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);
            }
        });
    }       
}
});