Reputation: 311
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 :)
Upvotes: 1
Views: 87
Reputation: 46
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.
Upvotes: 1
Reputation: 2432
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);
}
});
}
}
}]);
Upvotes: 2