如何在AngularJS中的指令中使用过滤日期

时间:2016-05-23 06:10:59

标签: angularjs angularjs-directive angularjs-filter

我的日期格式为ISO8601,我必须重新格式化它以格式化'dd / MM / yy HH:mm:ss'指令,但它不起作用。日期以原始格式显示。

指令:

app.directive('createTimeDirective', function ($filter) {
    return {
        restrict: 'E',
        template: '<div style="font-size: 9px;"> Created at {{date2}}<div>',
        //replace: true,
        scope: {
            date: '@'
        },
        link: function (scope, elem, attrs) {
            var dateFormat = 'dd/MM/yy HH:mm:ss';
            //scope.date = attrs.date;
            scope.date2 = $filter('date')(attrs.date, dateFormat);
            console.log(scope);

        }
    };
});

指令用法:

<create-time-directive date="'{{notices[$index].CreationTime}}'"></create-time-directive>|

1 个答案:

答案 0 :(得分:1)

是的,JB Nizet的答案很好:)。

但完整的解决方案就在这里:

指令用法(删除单引号):

<create-time-directive date="{{notices[$index].CreationTime}}"></create-time-directive>|

指令更新:

app.directive('createTimeDirective', ['$filter', function ($filter) {
    return {
        restrict: 'E',
        template: '<div style="font-size: 9px;"> Created at {{date2}}<div>',        
        scope: {
        date: '@'
    },
        link: function (scope, elem, attrs) {
            var dateFormat = 'dd/MM/yy HH:mm:ss';        
            scope.date2 = $filter('date')(attrs.date, dateFormat);            
        }
};
}]);