3

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?

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it works. Just the onFinish inside the div need to be on-finish. I cant edit it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.