1

Let's say I am creating a directive named 'shakeIt'. When signaled, this directive should add a class to the element it's applied on, after animation finishes, it should remove the class.

What is the best way to signal it to "shake" (add the class) without using events (I don't like using events, unless it's an event that is meant to be broadcasted/emitted globally).

Thanks :)

2
  • if you don't want to use events how about just watching a shaking scope variable in your directive that's set outside the directive Commented Jul 24, 2015 at 0:59
  • Thought about it, but it seems ugly :( Commented Jul 24, 2015 at 1:00

2 Answers 2

2

Use a property on your scope to track the state of the animation. Then pass the property to your directive:

<div shake-it="myScopeProp" duration="4000"></div>

This is what the directive might look like:

app.directive('shakeIt', ['$timeout', function($timeout){
  return {

    link: function($scope, $ele, $attr){
      $scope.$watch($attr.shakeIt, function(shaking){
        $ele.toggleClass('someClass', shaking);

        if(shaking){
          $timeout(function(){
            $scope[$attr.shakeIt] = false;
          }, $attr.duration);
        }
      });
    }
  }
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

Already tried it, it works. But I'm waiting to see if there is a cleaner solution available. Thanks anyways.
1

why do you want to create a directive when Angular provides ngClass directive.

In your controller, have a model which signals to shake it.

app.controller('ctrl', function($scope) {
  $scope.shakeIt = false;
});

while in HTML,

<p ng-class="{someClass : shakeIt}"> I'm shaking </p>

Now you have control when to shake it by changing model value to true. When animation finishes, change value to false.

Comments

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.