在 Angular 指令中的事件处理程序中调用范围函数

Calling scope function in event handler in Angular directive

本文关键字:调用 范围 函数 程序 Angular 指令 事件处理      更新时间:2023-09-26

>我的指令的链接函数中有以下代码:

    link: function (scope, element) 
        {
            angular.element($window).bind('resize', scope.layout);

        //  angular.element($window).bind('resize', function() 
        //  {
        //      scope.layout();
        //  });     

            scope.onImgLoad = function(e) {
                scope.ih=e.target.naturalHeight;
                scope.iw=e.target.naturalWidth;
                //scope.layout();
            };
            scope.layout = function() { 
               // do some style stuff based on image and window size
           }
}

当窗口大小调整发生时,我得到一个未定义的错误不是函数(scope.layout)我也尝试了注释的代码段,但我得到了同样的错误。如何在调整大小事件处理程序中调用链接范围内的函数?

更新

resize 事件正在父指令中查找布局函数。我通过给我的指令隔离范围来解决它。

scope.layout 函数在事件

上进行绑定时未定义resize

尝试将绑定放在函数定义之后。

 scope.layout = function() { 
               // do some style stuff based on image and window size
 }

 angular.element($window).bind('resize', scope.layout);

这里有一个 plunkr 解蒙(回调只执行一次): http://plnkr.co/edit/gUeKSYuUGEv9MT8idROg?p=preview

无论如何,如果不需要回调作为scope方法,您可以将其定义为:

function layout() { ... }

它将在执行的任何点可用。