【问题标题】:Not able to call function when directive loads指令加载时无法调用函数
【发布时间】:2020-06-07 21:23:40
【问题描述】:

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

我尝试在链接函数中调用该函数,但它抛出错误 TypeError: scope.setCurrent is not a function

这就是我尝试做的事情

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>

我不确定我哪里出错了。任何帮助将不胜感激

【问题讨论】:

    标签: angularjs angularjs-directive isolate-scope


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多