Building a Configurator in Angular

Introduction

Modl Buildr is a configurator that allows users to select and configure a product of choice. It was inspired by a desktop configurator application and the question, “How can this problem be solved better in the browser?.”

As with many of our projects, we used AngularJS. Built as a framework for enhancing and augmenting the HTML language, Angular provides developers with a toolset supporting web applications consisting of dynamic, data driven content. Angular’s primary components include services for the isolation of business logic, routing for application architecture, controllers for marshaling data and directives for concise templates and view. Modl Buildr is created on these four core concepts.

We introduced Modl Buildr in a previous blog post.

If you prefer a video exclamation to text, the video below explains how it works in considerable detail.

For text, read on.

Routing

Client side routing is needed in most non-trivial Angular applications. The router allows users to navigate between features of the application without the need for additional server round-trips. When establishing the routes of the application Modl Buildr takes advantage of the syntax and creates a declarative road map of the application’s “pages”. The state declarations that are added highlight what routes are available and their associated models, views and controllers. By utilizing the resolve mechanism it is immediately clear what pieces of data are needed in order for any given route to function properly. This also removes the need for the controller to communicate with an API service or contain promise handling boilerplate.

Controllers and Services

Connecting the models to the view are various combinations of controllers and services. The router takes advantage of custom services to allow the creation of clean, simple and maintainable controllers. Consider the following code used to connect the landing page’s view to its model.

Controller:

<br />
(function () {<br />
   'use strict';<br />
   angular.module('app.home', [])<br />
       .controller('HomeCtrl', function ($state, featuredProducts, popularProducts, productDataService) {<br />
           var hctrl = this;<br />
           hctrl.featured = featuredProducts;<br />
           hctrl.popular = popularProducts;<br />
           hctrl.selectProduct = selectProduct;</p>
<p>           //Prefetch for next route in navigation<br />
           productDataService.getProductList();</p>
<p>           function selectProduct(selectedProduct) {<br />
               $state.go('configure', {productId: selectedProduct.qsBaseID});<br />
           }<br />
       });<br />
}());<br />

Services:

<br />
that.getFeaturedList = function () {<br />
   return that.getProductList().then(function (list) {<br />
       return _.where(list, { Featured: true });<br />
   });<br />
};</p>
<p>that.getPopularList = function () {<br />
   return that.getProductList().then(function (list) {<br />
       return _.where(list, {Popular: true});<br />
   });<br />
};<br />

The code responsible for obtaining and shaping the data is isolated nicely in a service, consumed by the router, and made available to the controller. Meanwhile, the controller simply passes the data to the view. This MVVM (MVC, MVW*) pattern is seen throughout the application.

Not all of the controllers and services are this simple. Some data bindings require constant updating in the form functions. For example, as a user configures a product there is a significant amount of calculation that occurs to determine if the product’s configuration is still valid. The result of this calculation is bound to the view for the user to see. Best practices encourage a clean separation of controllers and services while allowing the service to take responsibility for complex computation. The following code snippet demonstrates how Modl Buildr achieves this separation while maintaining two way data binding.

<br />
(function () {<br />
   'use strict';<br />
   angular.module('app.configure')<br />
       .controller('ConfigureCtrl', function ($scope, $stateParams, $state,<br />
                    productDataService, productStateService,appStateService) {<br />
           var confCtrl = this;</p>
<p>           //the result of execution valid changes with every user input<br />
           confCtrl.valid = valid;<br />
           confCtrl.reset = reset;<br />
           confCtrl.goToSummary = goToSummary;<br />
           confCtrl.optionDisplay = optionDisplay;</p>
<p>           //Guard against extra API calls by only updating when the user’s selections have changed<br />
           $scope.$watchCollection(function () {<br />
               return confCtrl.selections;<br />
           }, function (n, o) {<br />
               if (n &amp;&amp; n._seriesId) {<br />
                  productDataService.getValidity(n).then(function () {<br />
                       updateAll();<br />
                   });<br />
               }<br />
           });</p>
<p>           function goToSummary() {<br />
               var modelNumber = productStateService.productOptions.BaseLabel;<br />
               modelNumber += _.map(productStateService.levelsToBuildModelNumber(), function (level) {<br />
                   return productStateService.selections[level.Tag];<br />
               }).join('');<br />
               $state.go(&quot;summary&quot;, {productId: productStateService.productOptions.qsBaseID, number: modelNumber});<br />
           }</p>
<p>           //This is called after every change to the user options<br />
           function updateAll() {<br />
               confCtrl.levels = productStateService.levelsToConfigure();<br />
               confCtrl.modelDisplayOptions = productStateService.levelsToBuildModelNumber();<br />
               confCtrl.valid = productStateService.valid;<br />
               confCtrl.selections = productStateService.selections;<br />
               confCtrl.productInfo = productStateService.productOptions;<br />
           }<br />
       });<br />
}());<br />

In the example above productInfo (the model number) and selections (the user’s choice of options) are bound to the view. The data in productInfo is a result of a function whose input is the selections. This approach not only provides a simple set of bindings, but also matches the application’s primary use case perfectly. The primary use case of the application is to select from a set of options and generate the corresponding model number. The challenge with this solution is that the server acts as a block box while performing the calculation. Fortunately the binding function is designed in such a way that it doesn’t matter where the complex calculation takes place or what it does. As the selections are updated the controller makes a service call and updates the bindings based upon the updated data that’s returned. The services handle the question of what to do and isolates the controller from any complexities or potential changes to this process.

Directives

There are several elements that appear on multiple screens of the application. These include simple pieces of functionality such as a hover text explaining why a button is disabled to custom widgets such as the product tiles. While controllers and services are great for laying out the big picture. Directives shine when used to create reusable and named components.

Modl Buildr contains a custom product tile directive. A reusable tile with a card-like appearance is created by combining a bootstrap panel, an image and a styled definition list. This tile is used to present products to the user. By specifying a few custom properties the same tile directive can be used across multiple situations.

Jade Template:

<br />
div.panel.panel-default.products-container(ng-click=&quot;click()&quot;,<br />
   ng-class=&quot;{'product-tile': configure==='false', 'configure-tile': configure==='true'}&quot;)<br />
   div.panel-heading<br />
       | {{product.BaseLabel}}<br />
       i.fa.fa-2x.fa-star.pull-right.featured(ng-show=&quot;product.Featured&quot;)<br />
   div.panel-body.product-details<br />
       img(ng-src=&quot;{{product.Image}}&quot;)<br />
       hr<br />
       dl.dl-horizontal.centered-block<br />
           dt Name:<br />
           dd {{product.BaseDesc}}<br />
           dt Mfr:<br />
           dd {{product.Manufacturer}}<br />
           dt Item Type:<br />
           dd {{product.ItemType}}<br />
           dt Subtype:<br />
           dd {{product.ItemSubType1}}<br />

Javascript:

<br />
(function () {<br />
   'use strict';<br />
   angular.module('app.tile', [])<br />
       .directive('descriptionTile', function () {<br />
           return {<br />
               restrict: 'E',<br />
               templateUrl: &quot;app/tile/descriptionTile.html&quot;,<br />
               scope: {<br />
                   product: '=info',<br />
                   click: '&amp;',<br />
                   configure: '@'<br />
               }<br />
           };<br />
       });<br />
}());<br />

With this definition and an ng-repeat these tiles are easily stamped out in a grid formation. This directive is also used on subsequent screens to display the product being configured.

Another helpful directive is the model number directive. The model number at the top of the configure and summary screens is generated by the users actions. Rather than complicate the main page controllers with the logic for displaying this interactive control a directive was created to isolate this concern. Now a model number can be displayed anywhere in the application by adding the following line of HTML (Jade) in the desired location:

<br />
model-number(product-name='{{cfg.productInfo.BaseLabel}}',<br />
    current-selections='cfg.modelDisplayOptions',<br />
    scroll-target='scroll-container')<br />
// (the above is Jade, http://jade-lang.com/<br />

Conclusions

Angular turned out to be a good fit for this application, yielding a working solution with a modest amount of code. Moreover, the application works quite nicely in a browser, at least as nicely as the native desktop application we were inspired by. The browser environment in 2015 is completely suitable for complex rules-based configurators.