AngularJS使用TypeScript和注入过滤

前端之家收集整理的这篇文章主要介绍了AngularJS使用TypeScript和注入过滤前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以向我提供一个示例,说明如何在TypeScript中使用依赖注入创建角度过滤器.在底部是我目前所拥有的,它工作正常,但我想要做的是我想要访问$filter的函数,以便我可以将行返回date.ToString()更改为$filter ‘日期’.这样我使用内置日期过滤器来显示一个友好的短期约会.
class FriendlyDateFilter {

    public static Factory() {
        return function (input): string {
            if (angular.isDate(input)) {
                var date: Date = input;
                var today = new Date();
                var days = Math.abs(getDaysBetweenDates(today,date));
                if (days < 7) {
                    var dayInWeek = date.getDay();
                    switch (dayInWeek) {
                        case 0:
                            return "Sunday";
                            break;
                        case 1:
                            return "Monday";
                            break;
                        case 2:
                            return "Tuesday";
                            break;
                        case 3:
                            return "Wednesday";
                            break;
                        case 4:
                            return "Thursday";
                            break;
                        case 5:
                            return "Friday";
                            break;
                        case 6:
                            return "Saturday";
                            break;
                    }
                } else {
                    return date.toString();
                }
            } else {
                return input;
            }
        }

        function getDaysBetweenDates(d0,d1) {
            var msPerDay = 8.64e7;

            // Copy dates so don't mess them up
            var x0: any = new Date(d0);
            var x1: any = new Date(d1);

            // Set to noon - avoid DST errors
            x0.setHours(12,0);
            x1.setHours(12,0);

            // Round to remove daylight saving errors
                return Math.round((x1 - x0) / msPerDay);
            }
        }

    }
}

angular.module("ReadingLog").filter("FriendlyDateFilter",FriendlyDateFilter.Factory);
在编写Angular过滤器时,通常最好使用函数模块而不是类.您可以像这样构造代码
function FriendlyDateFilter($filter) {
    return function (s: string): string {
        /* Your logic here */
    }
    /* Helper logic here */
}
module FriendlyDateFilter {
    export var $inject = ['$filter'];
}

angular.module("ReadingLog").filter("FriendlyDateFilter",FriendlyDateFilter);

如果您试图避免向全局范围添加太多,也可以将FriendlyDateFilter声明放在另一个模块中.

原文链接:https://www.f2er.com/angularjs/240600.html

猜你在找的Angularjs相关文章