Much of the benefit for using a framework like AngularJS lies in taking advantage of the client-side templating to boost your UI rendering by letting the client make the UI heavy lifting, while also avoiding having to render a new page every time the user makes a new request.

A downside to this is the addition of all those, sometimes unnecessary, roundtrips to the server. Although every so often the huge gains we get in user experience make it worth the extra calls, there are times when it makes sense to use the very first request to download not only the mandatory static assets (HTML/CSS/JavaScript) but also some initial data to bootstrap our AngularJS app.

You’ve probably seen this before as it is a very common pattern used to dynamically inject things like an object representing the user’s preferences and settings, environment variables, API urls, etc.

<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    <!-- script tags omitted -->
    <script>
        window.appConfig = {
            "siteUrl": "http://some.domain.com",
            "username": "johndoe",
            "language": "es-ES"
        };
    </script>
</head>  
<body>  
    <!-- body omitted -->
</body>  
</html>  

The biggest flaw is that it uses Globals. I won’t extend about JavaScript global variables because there’s plenty of literature online. Suffice it to say they are usually a bad idea.

Gladly, AngularJS gives us some great tools (namely constants and custom providers) that we can take advantage of and come up with an overall better solution.

Let’s replace that global variable with an AngularJS constant:

<!DOCTYPE html>  
<html ng-app="myApp">  
<head>  
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>@ViewBag.Title - My ASP.NET Application</title>
   <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js" type="text/javascript"></script>
   <script src="~/App/app.js"></script>
   <script>
        var appConfig = {
            "siteUrl": "http://some.domain.com",
            "username": "johndoe",
            "language": "es-ES"
        };

        angular.module('myApp.Constants', []).constant('appConfig', appConfig);
   </script>
</head>  
<body>  
   <!-- body omitted -->
</body>  
</html>  

Not only have we got rid of the global and all its baggage, but now AngularJS will use dependency injection to serve this constant in a safely manner whenever we need it:

(function () {
    'use strict';

    var app = angular.module('myApp', ['myApp.Constants']);

    function appCtrl(appConfig) {
        var vm = this;

        console.log(appConfig.username);
    }

    app.controller('appCtrl', ['appConfig', appCtrl]);
})();

Happy coding :)

Tags

JavaScript , AngularJS

Written by