Creating Custom Script Tag Directives In AngularJS
Earlier this week, I demonstrated that you could bind an AngularJS directive to multiple compilation and linking functions. At first, it might not be obvious as to why this is such a powerful feature. Not only does it mean that you can bind a single directive to multiple priorities, it also means that the existence of one directive does not automatically preclude the existence of another directive of the same name. I know this might sound like a horrible idea; but, consider the Script tag.
Out of the box, AngularJS provides a Script tag directive. This directive can be used to pre-populate the template cache so that directives don't have to make an additional HTTP request to load a template. It does this based on the Script tag type, "text/ng-template".
If you could only bind a single compilation and linking function to a given directive, this one use-case for the Script tag would prevent any other use-cases from being encapsulated within a directive. But, since you can bind multiple compilation and linking functions to the same directive, it means that we are free to define any number of Script tag directives, so long as they know to differentiate based on the Type.
To see this in action, I've put together a demo that uses both the native Script directive (text/ng-template) as well as a custom Script directive that can transpile ColdFusion code into AngularJS code using the type "text/cfml".
NOTE: This is not a robust compiler - just a fun little proof-of-concept.
As you can see, I have two different Script tags, side-by-side, in this AngularJS application. One uses the native AngularJS directive; one uses my CFML transpiler directive. And, when we run the above code, we get the following page output:
As you can see, the application is perfectly fine with two completely separate sets of Script tag compilation and linking functions. I know my demo is a silly little use-case; but, are you beginning to see potential?
Want to use code from this post? Check out the license.
Sencha does a similar way, and allows templates to imbed sub-templates, or functionality from any part of your app.
I'm loving the current iteration of major frameworks. Cool stuff.
It's definitely cool stuff. No matter how much progress I feel like I make in computer science, I look at the code in the Frameworks and I am always impressed. These frameworks guys are super smart!