2
\$\begingroup\$

I'm pretty new to AngularJS and have made my first directive. Is this a good or a bad way to do this? It works, but can't figure out if this is clever or not.

.directive('showWithDelay', function($timeout){
 return {
 restrict: 'A',
 link: function($scope, $element, attrs){
 $element.addClass("ng-hide");
 $timeout(function() {
 $element.removeClass("ng-hide");
 },attrs.showWithDelay);
 }
 }
})

Usage in template

<a class="button button-block rounded" show-with-delay="6000">CLICK ME</a>

button will be displayed after 6 sec.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 5, 2014 at 6:55
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Looks fine to me, I would add some small changes:

If you create a directive/service/controller/.. in Angular it's a best practice to create them with the [ ] notation to make sure minifying your code won't break:

.directive('name', [ '$timeout', function ($timeout) { 
} ] );

In your example a minifier would change the $timeout variable to something as 'a' which will result in an error because 'a' is not registered and thereby not known by Angular's dependency injection system.

In my example if a minifier would change $timeout it doesn't matter at all since a minifier doesn't change string values. A rule of thumb, always ngminify your code before jsminify.

And as last I would add a default value for the timeout function:

 $timeout(function () {
 $element.removeClass("ng-hide");
 }, attrs.showWithDelay || 5000);

This way if someone does not provide an attribute it will take the default value of 5000.

answered Oct 13, 2014 at 13:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.