表头可使用链接和范围选项使用AngularJS自定义指令进行排序

时间:2016-08-01 13:05:10

标签: angularjs angularjs-directive typescript angularjs-scope html-table

我想实现一个Angular指令,使表头可以排序。我尝试过以下方法:

HTML:

<th sortable="headers[0]">
    Company id
</th>
<th sortable="headers[1]">
    Client id
</th>

TypeScript Controller:

...
$scope.headers = [
    new Models.CampaignTableHeader("companyId", true, "Agency"),
    new Models.CampaignTableHeader("clientId", true, "Client"),
    new Models.CampaignTableHeader("clientName", true, "Client name"),
    new Models.CampaignTableHeader("name", true, "Campaign name")
];
...

TypeScript TableHeader Model:

export class CampaignTableHeader {
    public asce: boolean;
    public desc: boolean;
    public css: () => string;

    constructor(
        public id: string,
        public sortable: boolean = false,
        public title?: string
    ) {
        if (_.isNull(title) || _.isUndefined(title)) {
            this.title = id;
        }
        this.asce = false;
        this.desc = false;
        this.css = () => {
            var result = this.sortable ? "sortable" : "";
            if (this.asce) {
                result = "sortable-asce " + result;
            }
            else if (this.desc) {
                result = "sortable-desc " + result;
            }
            return result;
        }
    }
}

TypeScript Main:

var cuidApp = angular
.module("mainModule", [])
.controller("mainController", ["$scope", "$http", "$window", "$timeout", "$q", Controllers.MainController])
.directive("sortable", () => {
    return {
        link: (scope: any, element, attrs) => {
            var value: Models.CampaignTableHeader = scope.sortable;
            console.log(scope.sortable);
            var e = $(element);
            e.attr("ng-class", "sortable.css()");
        },
        scope: {
            sortable: "="
        }
    }
});

console.log(scope.sortable)输出预期的CampaignTableHeader对象。问题是ng-class指令没有正确的范围。我在控制台中检查了header元素的范围,但它没有sortable属性。你知道我应该改变它的工作吗?

0 个答案:

没有答案