Use AngularJS and ngHref to Grab CSS Dynamically

Free Course

Getting Started with Angular 2

Angular 2 is the shiny new framework that comes with a lot of new concepts. Learn all the great new features.

Angular helps us build a great many things and the directives it provides make development much easier. Today we’ll be looking at the ngHref and how we can use it to build a demo site to show off to others.

We will be able to change out resources (like CSS) on the fly. We’ve all seen the WordPress theme demos where you can select different style options (colors, layout, etc). Here’s an image of what we’ll be building and be sure to check out the demo.

angular-nghref-demo

Let’s build it in Angular now!

The ngHref Directive

When creating links that have bound variables within it, it can cause problems for our users. For example, here’s a link with a variable inside of it:

<a href="http://facebook.com/{{ username }}">Facebook Page</a>

This link could go to the wrong place if a user happens to click it before Angular gets a chance to change out the URL. The solution here is to use the ngHref directive.

<a ng-href="http://facebook.com/{{ username }}">Facebook Page</a>

This way, the directive will make sure that all variables inside of the href tag are updated before the user has a chance to click.

Now let’s look at a different scenario where we can use Angular to dynamically pull in CSS files.

Building Our Demo Site

Again, here’s the quick demo of how we’ll be changing out CSS on the fly to create a demo site. This technique could be used to change out any number of resources, from JS to CSS to links.

This is also good to have since we can separate out experimental stylesheets for a project. For this project, we have a few different layouts that we want to try and see how it would look with different Bootstrap swatches from Bootswatch.

Let’s write up our quick demo so we can see exactly how it works. We’ll start with the Angular app since that will be an easy affair. We’ll be pulling in CSS from BootstrapCDN) and creating our own custom CSS files for the layouts.

Angular Module


    angular.module('linkApp', [])

    .controller('mainController', function($scope) {
      
      // set the default bootswatch name
      $scope.css = 'cosmo';
       
      // create the list of bootswatches
      $scope.bootstraps = [
        { name: 'Basic', url: 'cosmo' },
        { name: 'Slate', url: 'slate' },
        { name: 'Sandstone', url: 'sandstone' }
      ];
      
      // set the default layout
      $scope.layout = 'normal';
      
      // create the list of layout files
      $scope.layouts = [
        { name: 'Boring', url: 'normal' },
        { name: 'Circles', url: 'circle' },
        { name: 'In Your Face', url: 'large' }
      ];

    });

We have created a quick Angular module and controller where we define a list of both Bootstrap (we’ll be switching out Bootswatch theme files) on the fly. We are also defining layouts that are custom CSS files that we have created for this project.

We have set our base styles also with $scope.css and $scope.layout. We’ll use these in our HTML file.

The View File


<!DOCTYPE html>

<!-- define our app and controller on html -->
<html ng-app="linkApp" ng-controller="mainController">

<head>

    <!-- pull in css based on angular -->
    <link rel="stylesheet" ng-href="//maxcdn.bootstrapcdn.com/bootswatch/3.2.0/{{ css }}/bootstrap.min.css">
    <link rel="stylesheet" ng-href="layout-{{ layout }}.css">
    <style>
        body {
            padding-top: 50px;
        }
    </style>

    <!-- bring in JS and angular -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
    <script src="app.js"></script>
</head>

<body class="container">

    <!-- our content -->
    <div class="picture-thing">
        <div class="picture-thing-img">
            <img src="https://cask.scotch.io/2014/10/picture-picture.jpg">
        </div>
        <div class="picture-thing-content">
            <h2>Bananas</h2>
            <p>This demo is just that.</p>
        </div>
    </div>
    
</body>
</html>

The main part we want to look at here is how we pull in CSS files. This is a different example of using ng-href than we showed off earlier since we’re using it on a link tag instead of the a tag. The effect is the same however.


    <!-- pull in css based on angular -->
    <link rel="stylesheet" ng-href="//maxcdn.bootstrapcdn.com/bootswatch/3.2.0/{{ css }}/bootstrap.min.css">
    <link rel="stylesheet" ng-href="layout-{{ layout }}.css">

Notice how we are placing the {{ css }} variable inside of the ng-href. We’ll be using BootstrapCDN, under the Bootswatch tab, to grab our CSS files.

Since we have already defined those variables, our site will use those by default. Next up, we have to give our user the ability to change out those variables so we’ll be building dropdown selects to show off the options we created earlier.

Providing User Inputs

We will need to give users the options to select a different theme or layout. We’ll do this at the top of our HTML file and use another Angular directive, ngOptions to display our two lists of resources.

At the top of our HTML file, after the opening <body> tag, add the following:

<!-- section to select styles -->
    <div class="well">
        <form>

            <div class="form-group">
                <label>Theme</label>
                <select class="form-control" ng-model="css" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">
                </select>
            </div>

            <div class="form-group">
                <label>Layout</label>
                <select class="form-control" ng-model="layout" ng-options="layout.url as layout.name for layout in layouts"></select>
            </div>

        </form>
    </div>

    <hr>

Now we have the options necessary to change out the styles.

angular-nghref-options

If you go ahead and select different Themes, they will immediately be applied to our site! The layouts won’t change anything though since we haven’t defined those styles yet. Let’s do that now and change up the look and feel of our picture-thing div.

CSS Layouts

These will be simple CSS files to show off how we can change the look and feel of our content quickly. Since the foundation is already set using ng-href and our list of options, once we create these files, everything will work!

We’ll be using CSS transitions and just some basic styling here that we won’t go over in too much detail.

layout-normal.css

.picture-thing-img img { width:200px; }
angular-nghref-basic

layout-circle.css

.picture-thing {
    display: block;
    width: 400px;
    height: 400px;
    overflow: hidden;
    margin: 0 auto;
    border-radius: 50%;
}
.picture-thing-img img {
    max-width: 200%;
}
.picture-thing-content {
    text-align: center;
    color: #FFF;
    transition: 0.3s ease all;
    opacity: 0;
}
.picture-thing-content h2 {
    font-size: 40px;
}
.picture-thing-content p {
    font-size: 25px;
}
.picture-thing: hover .picture-thing-content {
    transform: translateY(-375%);
    opacity: 1;
}
angular-nghref-circles

layout-large.css

.picture-thing {
    display: block;
    width: 400px;
    height: 400px;
    overflow: hidden;
    margin: 0 auto;
    border-radius: 50%;
}
.picture-thing-img img {
    max-width: 200%;
}
.picture-thing-content {
    text-align: center;
    color: #FFF;
    transition: 0.3s ease all;
    opacity: 0;
}
.picture-thing-content h2 {
    font-size: 40px;
}
.picture-thing-content p {
    font-size: 25px;
}
.picture-thing: hover .picture-thing-content {
    transform: translateY(-375%);
    opacity: 1;
}
angular-nghref-demo

Now we have all three of our stylesheets and setup necessary to have a working demo site. Go back into your site and just try changing a few things. You’ll see them change quickly as it grabs the new stylesheets.

Conclusion

Using one of the built in Angular directives, we are able to build in some cool and quick functionality. There are plenty of uses for this whether it be showcasing a site to a client and trying out different styles or maybe creating an interactive site that pulls in any number of different resources.

For more info on Angular directives, here are some other articles detailing a few:

Chris Sevilleja

Co-founder of Scotch.io. Slapping the keyboard until something good happens.