angularjsangularjs-directiveisolate-scope

Not able to call function when directive loads


I'm working on AngularJS custom directive. I'm trying to call a function as soon as my directive loads.

I tried calling the function within link function, but it's throwing error as TypeError: scope.setCurrent is not a function.

Here's what I tried to do

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


function dirPaginationControlsLinkFn(scope, element, attrs){
    var vm = this;
    scope.setCurrent(1);    //this function is throwing error

    scope.setCurrent = function(num) {     //working fine
        scope.GetPager(scope.totalData,num,3);
    };
}

The same setCurrent(data) function is working fine when I'm triggering a click event

<li ng-repeat="pages in pages track by $index">
  <a ng-click="setCurrent(pages)">{{ pages }}</a>
</li>

I'm not sure where I'm going wrong. Any help would be appreciated


Solution

  • problem is that you call function before declaration that is why setCurrent is not defined.

        scope.setCurrent = function(num) {     //first declare function and initialling with body 
            scope.GetPager(scope.totalData,num,3);
        };
    
        scope.setCurrent(1);    //than call function