Binding Scripts & Stylesheets To States With AngularJS (UIRouter)

AngularJS combined with UIRouter is a powerful and fast client-side combination for routing and rendering nested views. There’s one thing that needs some special attention though. Angular expects us to include the same, or all of our scripts and styles in the parent-most view. What if we want sylesheets or scripts coupled with specific states? Here’s a solution.

Lets start by creating an index.html file and preparing it for an angular application.

Note the div elements I’ve created for our stylesheets and scripts? Yeah? Good.

Now let’s hook up some states in angular.app.js, dude!

I’ve added two arrays to the login state to contain some script and stylesheet references that we’ll be adding to the document object model. This next part is my favourite, and makes use of the app’s rootScope.

When the state begins to change, the global variables (above) will be assigned the said arrays we’ve coupled with the state. Just before the view content gets rendered by the browser, these calls to rootScopeMechanism will fire, and be passed the arrays as arguments – appending new HTML elements to the DOM.

Boom. Suckas. This root scope mechanism will now bind scripts and stylesheets to our states!