加载指令后无法调用函数

时间:2020-02-24 09:15:47

标签: angularjs angularjs-directive isolate-scope

我正在研究AngularJS自定义指令。我正在尝试在指令加载后立即调用函数。

我尝试在链接函数中调用该函数,但由于 TypeError:scope.setCurrent不是函数而引发错误。

这就是我想要做的

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);
    };
}

当我触发点击事件时,相同的 setCurrent(data)函数可以正常工作

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

我不确定我要去哪里。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

问题是您在声明之前调用了函数,这就是为什么未定义setCurrent的原因。

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

    scope.setCurrent(1);    //than call function 
相关问题