0

I have the following code in the link function of my directive:

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

When the window resize happens I get an error undefined is not a function (scope.layout) I also tried the commented piece of code but I got the same error. How can i call a function within the link scope in the resize event handler?

Update

The resize event was looking for a layout function in the parent directive. I solved it by giving my directive isolated scope.

Michiel
  • 4,160
  • 3
  • 30
  • 42

1 Answers1

0

The scope.layout function is not defined when you make the binding on resize event.

Try to put the binding after the function definition.

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


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

Here a plunkr demontration (the callback is executed only once): http://plnkr.co/edit/gUeKSYuUGEv9MT8idROg?p=preview

Anyway if don't need the callback as a scope method you can define it as:

function layout() { ... }

and it will be available at any point of the execution.

marquez
  • 737
  • 4
  • 10
  • Marquez, the order did not matter, after i found the solution I switched the statements as you suggested, but it works either way. – Michiel Dec 01 '14 at 09:06
  • I'm glad you find a solution. But if you look at the plunkr code you'll se that the order has effect when you define a function as an expression. This is not my opinion is a fact. You can check this answer too http://stackoverflow.com/questions/3887408/javascript-function-declaration-and-evaluation-order – marquez Dec 01 '14 at 12:05