Stefan
Stefan

Reputation: 1071

pass callback to directive - angularjs

I try to add an animation to an element via a directive. When the animation is done I want it to call the passed callback function. I try to do achieve it this way (SO - How to add validation attributes in an angularjs directive)

The 'addAnimation' directive:

angular.module('myModule')
  .directive('addAnimation', function ($compile) {
    return {
      restrict: 'A',
      scope: {
        onFinish:"&"
      },
      replace: false,
      terminal: true,
      priority: 1000,
      link: function (scope, element, attrs) {
        element.on('click', function() {           
          $('.selector').animate({ ... }), function() {
            if(attrs.cb) {
              attrs.cb.onFinish();
            }
          });             
        })

        element.removeAttr("addAnimation"); //remove the attribute to avoid indefinite loop

        $compile(element)(scope);
      }
    };
  });

The directive 'aDirective' the animation should be added to:

angular.module('myModule')
  .directive('aDirective', function () {
    return {
      templateUrl: 'path/to/template.html',
      restrict: 'EA',
      link: function (scope, element, attrs) {
        scope.test = function() {
          console.log('this should be logged');
        }
      }
    };
  });


<div>
  <div add-animation cb="{onFinish: 'test'}"></div>
</div>

When I click it, the animation starts, but then I get the error:

Uncaught TypeError: attrs.cb.onFinish is not a function

Logging attrs.cb seems like its not resolving the function:

{onFinish: 'test'}

What am I doing wrong here?

Upvotes: 3

Views: 2923

Answers (1)

Tomek Sułkowski
Tomek Sułkowski

Reputation: 7201

You have defined onFinish on the directive's scope, you should use it like on scope, It needs to be used in the element as on-finish,so instead of:

attrs.cb.onFinish()

do

scope.onFinish()

Also, if you define it like this:

scope: {
    onFinish:"&"
},

you should pass it into the directive this way:

<div add-animation on-finish="test()"></div>

Upvotes: 3

Related Questions