An approach to Angular separation of concerns

Filipe Ximenes
March 20, 2015
<p><a href="">Angular.js</a> is a great JavaScript framework, it makes easy to develop Single Page Applications (SPAs) and removes most of the pain regarding data binding, requests and routing.</p><p><br>Unlike many MVW (Model View Whatever) frameworks and because the way JavaScript works, it does not force us to organize projects in a specific way nor it defines where each piece of code goes in your projects (where do we initialize model variables: controllers? services?).</p><p><br>I've read many blog posts talking about interesting design patterns and project architectures that define how to organize code and make a clean Angular project. So, just for fun, I decided to write a little app trying to follow the patterns which I liked the most. By the end, I had a simple app with some interesting concepts, especially regarding separation of concerns, so I decided to share them hoping to get some feedback. The code is available in my GitHub:</p><p><a href=""></a></p><p>It's a Django app that allows users to enter and edit times for their jogging activities. The API is powered by <a href="">Django REST Framework</a>, but for this post I want to focus on the Angular part, so please just ignore the rest of the project.</p><h2 id="the-architecture">The Architecture</h2><p>For the architecture I decided to go with an "app driven" pattern, where each app is [almost] self contained and has its own modules (Controllers, Services, etc). This is how most people recommend organizing the code when working in real world projects. Django developers will find this pattern pretty familiar.</p><figure class="kg-card kg-code-card"><pre><code>/main.module.js /core /core.module.js /core.ctrl.js /core.service.js /accounts /accounts.module.js /accounts.ctrl.js /accounts.service.js /timings /timings.module.js /timings.ctrl.js /timings.service.js </code></pre><figcaption><a href="">Click here to see it in the project</a></figcaption></figure><h2 id="the-main-module">The main module</h2><p>The way it's organized, the main module (<code>main.module.js</code>) is responsible to defining dependencies, setting global configurations and routing. <a href="">Take a look here</a>.</p><h2 id="app-modules">App Modules</h2><p>Each app has a module file, responsible to naming it and declaring the internal dependencies.</p><pre><code class="language-javascript">(function (){ var app = angular.module('Jogging.timings', ['Jogging.timings.ctrl', 'Jogging.timings.service']); })(); </code></pre><p>This also makes it easy to import apps in the main module:</p><pre><code class="language-javascript">var app = angular.module('Jogging', [ ... 'Jogging.core', 'Jogging.accounts', 'Jogging.timings']); </code></pre><h2 id="restangular">Restangular</h2><p>Before going to the main part of this article, just a brief note:<br>Angular <code>$http</code> service is nice. I mean, its simple enough and does most of what is expected from it. On the other side, Restangular is just great! It allows us to set global configurations like the base url, and has very clean interface to play with web APIs. I really recommend <a href="">taking a look at the project</a>.</p><h2 id="controllers-and-services">Controllers and Services</h2><p>Now to the interesting parts! The main rule I tried to follow during the development of this app was:</p><p><code>Keep STATE and LOGIC inside services and make extremely thin controllers</code></p><p>This way, controllers are simply the interface between template and the services.</p><p>Lets take a look on how timings are managed:</p><p><a href="">TimingsFactory</a>:</p><pre><code class="language-javascript">app.factory('TimingsFactory', ['Restangular', 'ConversionFactory', function (Restangular, ConversionFactory){ var timingsResource = Restangular.all('timings'); obj = {}; obj.timings = []; obj.getTimingList = function (filters){ return timingsResource.getList(filters).then(function(response) { obj.timings =; }); }; obj.createTiming = function (data){ data.time = ConversionFactory.fromFormattedToSeconds(createData.formattedTime); return (response){ obj.timings.push(; }); }; obj.updateTiming = function (index, data){ var timingResource ='timings', obj.timings[index].id); angular.extend(timingResource, data); return timingResource.put().then(function (response){ angular.extend(obj.timings[index],; }); }; obj.deleteTiming = function (index){ var timingResource ='timings', obj.timings[index].id); timingResource.remove().then(function (response){ obj.timings.splice(index, 1); }); }; return obj; } ]); </code></pre><p>As we can see, the <code>TimingsFactory</code> provides <code>obj.timings</code> variable responsible for the state of the timings list and all functions that perform actions on it (in this case, a simple CRUD).</p><p>The controller will only add the TimingsFactory to the <code>$scope</code>:</p><p><a href="">TimingsCtrl</a>:</p><pre><code class="language-javascript">app.controller('TimingsCtrl', ['$scope', 'TimingsFactory', 'ConversionFactory', 'ReportsFactory', function ($scope, TimingsFactory, ConversionFactory, ReportsFactory){ $scope.timingsFactory = TimingsFactory; ... } ]); </code></pre><p>And service functions are called directly from the template. For example:</p><p>The <a href="">form to create a timing</a>:</p><pre><code class="language-html">&lt;form class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;label for="time"&gt;Time: &lt;/label&gt; &lt;input data-ng-model="createData.formattedTime" name="time" type="text" class="form-control"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="distance"&gt;Distance: &lt;/label&gt; &lt;input data-ng-model="createData.distance" name="distance" type="number" class="form-control"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="date"&gt;Date: &lt;/label&gt; &lt;input data-ng-model="" name="date" type="date" class="form-control"&gt; &lt;/div&gt; &lt;button data-ng-click="timingsFactory.createTiming(createData); createData = {};" class="btn btn-default"&gt;add&lt;/button&gt; &lt;/form&gt; </code></pre><p><a href="">Filtering timings</a>:</p><pre><code class="language-html">&lt;form class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;label for="startDate"&gt;From: &lt;/label&gt; &lt;input data-ng-model="filters.start_date" type="date" name="startDate" class="form-control"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="endDate"&gt;To: &lt;/label&gt; &lt;input data-ng-model="filters.end_date" type="date" name="endDate" class="form-control"&gt; &lt;/div&gt; &lt;button data-ng-click="timingsFactory.getTimingList(filters);" class="btn btn-default"&gt;filter&lt;/button&gt; &lt;/form&gt; </code></pre><p>If you want to see some more: <a href="">the listing and inline performing updates in timings.</a></p><h2 id="separating-concerns">Separating concerns</h2><p>The timings area was easy, all interactions only affected the state of the timings list which were already in the service. So, how to deal with service operations that also affect other <code>$scope</code> data. Lets look at the login process.</p><p>If user correctly enters login info, we expect it to be redirected to the <code>/timings</code> controller, otherwise, provide a visual feedback that there was a problem.</p><p>To do this, the <a href="">AccountFactory</a> will receive an object containing envents to be executed after the resquest was made.</p><p>The <a href="">performLogin</a> function:</p><pre><code class="language-javascript">this.performLogin = function (data){ Restangular.all('login').post(data) .then(function (response){ _this.setCredentials(; if (events.onPerformLoginSuccess){ return events.onPerformLoginSuccess(response); } }, function (response){ if (events.onPerformLoginFailure){ return events.onPerformLoginFailure(response); } }); }; </code></pre><p>and this is how <code>AccountFactory</code> is instantiated:</p><p><a href="">LoginController</a></p><pre><code class="language-javascript">app.controller('LoginController', ['$scope', '$location', 'AccountFactory', function ($scope, $location, AccountFactory){ $scope.accountFactory = new AccountFactory({ onPerformLoginSuccess: function (response){ $location.path('/timings'); }, onPerformLoginFailure: function (response){ $scope.loginFailure = true; } }); } ]); </code></pre><h2 id="that-s-all-for-now">That's all for now</h2><p>So here is what I have to show for now, hope you all liked. Please leave a comment with your opinions so this can be improved!</p>