加载指令后调用函数

call a function after directive is loaded

我正在研究 angular 1.6

的自定义指令

我想在我的指令加载后调用一个函数。有办法实现吗?

我尝试了 link 函数,但似乎 link 函数在指令加载之前执行。

任何帮助将不胜感激。

这是我的指令代码

<pagination total-data= noOfRecords></pagination>
app.directive("pagination", [pagination]);

function pagination() {
    return {
        restrict: 'EA',
        templateUrl: 'template/directives/pagination.html',
        scope: {
            totalData: '=',
        },
        link: dirPaginationControlsLinkFn
    };
}

您可以尝试在 $onInit()$postLink() docs might help

内调用您的函数

您可以在 link 函数中向 totalData 添加一个监视并在那里执行操作。

scope.$watch('totalData', function () {
   if (scope.totalData && scope.totalData.length > 0) { //or whatever condition is required
   }
});

由于您使用的是 AngularJS V1.6,请考虑将该指令作为一个组件:

app.component("pagination", {
    templateUrl: 'template/directives/pagination.html',
    bindings: {
        totalData: '<',
    },
    controller: "paginationCtrl"
})

并使用 $onChanges$onInit life-cycle hooks:

app.controller("paginationCtrl", function() {
    this.$onChanges = function(changesObj) {
        if (changesObj.totalData) {
            console.log(changesObj.totalData.currentValue);               
            console.log(changesObj.totalData.previousValue);                 
            console.log(changesObj.totalData.isFirstChange());
        };
    };
    this.$onInit = function() {
        //Code to execute after component loaded
        //...
    });
});

组件是指令结构,它们可以自动升级到 Angular 2+ 组件。他们使迁移到 Angular 2+ 更容易。

有关详细信息,请参阅