In the first part of this post, we refactored a jQuery code block into a pretty simple but limited directive.
Now it’s time to refactor our directive by removing the pages fixed amount limitation.
Just to recap, below is the directive we did:
We use 'data-' prefix to make sure html validates and we do not cause IE7, 8 browsers to go into quirks mode. Very Important!!!!
We use 'my-' prefix to determine this is a custom directive that belongs to our team.
Even though we add more span/pages in the above HTML, our directive doesn’t consider them since the switch block’s logic is only covering the first four “span” elements.
Let’s consider the following:
The “active” class would never be assigned to any “span” element beyond the forth one. (in this case the “Post Sale” “span” element)
We said we were going to show you a more flexible way of coding this directive. This way actually involves having a non-fixed number of pages. Taking advantage of this change, we're going to code this directive in a slighty different way.
Our new directive should look like:
In this case the directive has one extra attribute -“data-pages”-, which is intended to hold an array of page names.
This way we can get rid of the fixed number of pages from our previous simple example.
The array of pages is hardcoded in this example but it may be coming from a scope attribute dynamically generated in a controller, service, etc.
As always the test comes first. Let's use the first one from the previous post and update the HTML with our new code:
Please note that expectations were not changed. Even though the code was updated, the result shouldn’t change.
Remember that after compiling the code, our directive applies the “active” CSS class to the corresponding element based on the current page(index) attribute.
Let's write more tests changing the number of pages and the CSS selector for the page the user is on:
Having finished writting the tests, it's now time to write the new directive code:
Let’s have a look at the “myTemplate.html” file:
So now each html has:
Let’s point out that:
the directive is declared to be used as an attribute (“restrict” attribute)
the directive HTML code related is extracted and placed into a new separated file (“templateUrl” attribute)
the directive defines its inner scope with variables (“scope” attribute)
the “link” function has been commented since the logic is now applied on the template html.
Note: the real-world directive should have more code written (for instance some validation on the page number or CSS) but that is not the purpose of this post and is totally out of scope.-
Having updated the original code, we are able to provide different quantities of pages and their corresponding names.