Reputation: 447
I am working on custom directive of angular 1.6
I want to call a function after my directive is loaded. Is there a way to achieve this?
I tried link function, but it seems the link function is executed before the directive is loading.
Any help will be appreciated.
This is my directive code
<pagination total-data= noOfRecords></pagination>
app.directive("pagination", [pagination]);
function pagination() {
return {
restrict: 'EA',
templateUrl: 'template/directives/pagination.html',
scope: {
totalData: '=',
},
link: dirPaginationControlsLinkFn
};
}
Upvotes: 1
Views: 626
Reputation: 48948
Since you are using AngularJS V1.6, consider making the directive a component:
app.component("pagination", {
templateUrl: 'template/directives/pagination.html',
bindings: {
totalData: '<',
},
controller: "paginationCtrl"
})
And use the $onChanges
and $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
//...
});
});
Components are directives structured in a way that they can be automatically upgraded to Angular 2+ components. They make the migration to Angular 2+ easier.
For more information, see
Upvotes: 1
Reputation: 796
You might add a watch to totalData in link function and do the stuff there.
scope.$watch('totalData', function () {
if (scope.totalData && scope.totalData.length > 0) { //or whatever condition is required
}
});
Upvotes: 1
Reputation: 3856
You can try calling your function inside $onInit()
or inside $postLink()
docs might help
Upvotes: 0