AngularJS: Understanding design pattern


  • Controller should be just an interlayer between model and view. Try to make it as thin as possible.
  • It is highly recommended to avoid business logic in controller. It should be moved to model.
  • Controller may communicate with other controllers using method invocation (possible when children wants to communicate with parent) or $emit, $broadcast and $on methods. The emitted and broadcasted messages should be kept to a minimum.
  • Controller should not care about presentation or DOM manipulation.
  • Try to avoid nested controllers. In this case parent controller is interpreted as model. Inject models as shared services instead.
  • Scope in controller should be used for binding model with view and
    encapsulating View Model as for Presentation Model design pattern


Treat scope as read-only in templates and write-only in controllers. The purpose of the scope is to refer to model, not to be the model.

When doing bidirectional binding (ng-model) make sure you don’t bind directly to the scope properties.


Model in AngularJS is a singleton defined by service.

Model provides an excellent way to separate data and display.

Models are prime candidates for unit testing, as they typically have exactly one dependency (some form of event emitter, in common case the $rootScope) and contain highly testable domain logic.

  • Model should be considered as an implementation of particular unit. It is based on single-responsibility-principle. Unit is an instance that is responsible for its own scope of related logic that may represent single entity in real world and describe it in programming world in terms ofdata and state.
  • Model should encapsulate your application’s data and provide an API to access and manipulate that data.
  • Model should be portable so it can be easily transported to similar application.
  • By isolating unit logic in your model you have made it easier to locate, update, and maintain.
  • Model can use methods of more general global models that are common for the whole application.
  • Try to avoid composition of other models into your model using dependency injection if it is not really dependent to decrease components coupling and increase unit testability and usability.
  • Try to avoid using event listeners in models. It makes them harder to test and generally kills models in terms of single-responsibility-principle.

Model Implementation

As model should encapsulate some logic in terms of data and state, it should architecturally restrict access to its members thus we can guarantee loose coupling.

The way to do it in AngularJS application is to define it using factory service type. This will allow us to define private properties and methods very easy and also return publically accessible ones in single place that will make it really readable for developer.


.factory( 'searchModel', ['searchResource', function (searchResource) {

  var itemsPerPage = 10,
  currentPage = 1,
  totalPages = 0,
  allLoaded = false,

  function init(params) {
    itemsPerPage = params.itemsPerPage || itemsPerPage;
    searchQuery = params.substring || searchQuery;

  function findItems(page, queryParams) {
    searchQuery = queryParams.substring || searchQuery;

    return searchResource.fetch(searchQuery, page, itemsPerPage).then( function (results) {
      totalPages = results.totalPages;
      currentPage = results.currentPage;
      allLoaded = totalPages <= currentPage;

      return results.list

  function findNext() {
    return findItems(currentPage + 1);

  function isAllLoaded() {
    return allLoaded;

  // return public model API  
  return {
     * @param {Object} params
    init: init,

     * @param {Number} page
     * @param {Object} queryParams
     * @return {Object} promise
    find: findItems,

     * @return {Boolean}
    allLoaded: isAllLoaded,

     * @return {Object} promise
    findNext: findNext

Creating new instances

Try to avoid having a factory that returns a new able function as this begins to break down dependency injection and the library will behave awkwardly, especially for third parties.

A better way to accomplish the same thing is to use the factory as an API to return a collection of objects with getter and setter methods attached to them.

 .factory( 'carModel', ['carResource', function (carResource) {

  function Car(data) {
    angular.extend(this, data);

  Car.prototype = {
    save: function () {
      // TODO: strip irrelevant fields
      var carData = //...

  function getCarById ( id ) {
    return carResource.getById(id).then(function (data) {
      return new Car(data);

  // the public API
  return {
    // ...
    findById: getCarById
    // ...

Global Model

In general try to avoid such situations and design your models properly thus it can be injected into controller and used in your view.

In particular case some methods require global accessibility within application. To make it possible you can define ‘common’ property in $rootScope and bind it to commonModel during application bootstrap:

angular.module('app', ['app.common'])
.run(['$rootScope', 'commonModel', function ($rootScope, commonModel) {
  $rootScope.common = 'commonModel';

All your global methods will live within ‘common’ property. This is some kind of namespace.

But do not define any methods directly in your $rootScope. This can lead to unexpected behaviorwhen used with ngModel directive within your view scope, generally littering your scope and leads to scope methods overriding issues.


Resource lets you interact with different data sources.

Should be implemented using single-responsibility-principle.

In particular case it is a reusable proxy to HTTP/JSON endpoints.

Resources are injected in models and provide possibility to send/retrieve data.

Resource implementation

A factory which creates a resource object that lets you interact with RESTful server-side data sources.

The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service.


Both model and resource are services.

Services are unassociated, loosely coupled units of functionality that are self-contained.

Services are a feature that Angular brings to client-side web apps from the server side, where services have been commonly used for a long time.

Services in Angular apps are substitutable objects that are wired together using dependency injection.

Angular comes with different types of services. Each one with its own use cases. Please readUnderstanding Service Types for details.

Try to consider main principles of service architecture in your application.

In general according to Web Services Glossary:

A service is an abstract resource that represents a capability of performing tasks that form a coherent functionality from the point of view of providers entities and requesters entities. To be used, a service must be realized by a concrete provider agent.

Client-side structure

In general client side of the application is splitted into modules. Each module should be testable as a unit.

Try to define modules depending on feature/functionality or view, not by type. See Misko’s presentation for details.

Module components may be conventionally grouped by types such as controllers, models, views, filters, directives etc.

But module itself remains reusable, transferable and testable.

It is also much easier for developers to find some parts of code and all its dependencies.

Please refer to Code Organization in Large AngularJS and JavaScript Applications for details.

An example of folders structuring:

|-- src/
|   |-- app/
|   |   |-- app.js
|   |   |-- home/
|   |   |   |-- home.js
|   |   |   |-- homeCtrl.js
|   |   |   |-- home.spec.js
|   |   |   |-- home.tpl.html
|   |   |   |-- home.less
|   |   |-- user/
|   |   |   |-- user.js
|   |   |   |-- userCtrl.js
|   |   |   |-- userModel.js
|   |   |   |-- userResource.js
|   |   |   |-- user.spec.js
|   |   |   |-- user.tpl.html
|   |   |   |-- user.less
|   |   |   |-- create/
|   |   |   |   |-- create.js
|   |   |   |   |-- createCtrl.js
|   |   |   |   |-- create.tpl.html
|   |-- common/
|   |   |-- authentication/
|   |   |   |-- authentication.js
|   |   |   |-- authenticationModel.js
|   |   |   |-- authenticationService.js
|   |-- assets/
|   |   |-- images/
|   |   |   |-- logo.png
|   |   |   |-- user/
|   |   |   |   |-- user-icon.png
|   |   |   |   |-- user-default-avatar.png
|   |-- index.html

Good example of angular application structuring is implemented by angular-app

This is also considered by modern application generators –





Html.RenderPartial() syntax with Razor

  • RenderPartial() is a void method that writes to the response stream. A void method is, in C#, needs a ; and hence must be enclosed by { }.
  • Partial() is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @ prefix to distinguish it from plain HTML you have on the page.

ASP.NET MVC Pro’s and Con’s

In our current iteration of improving our software development strategy, ASP.NET WebForms simply doesn’t fit in with the new demands of being unit testable and flexible. It comes as no surprise that ASP.NET MVC has been getting all the headlines lately. Like many others, I’ve gotten the itch to try it out. In this post I’ll talk about what I believe are the main pro’s and con’s of the new style for building web applications.


PRO – No ViewState or “surprise crap”

In traditional ASP.NET WebForms, the luxury of pretending to behave like a Windows Form comes at a price. The ViewState is a reliable way of storing all of the state information for the form. Unfortunately, due to the limitations of the web, this data needs to be a giant string inside of a hidden form field. This ends up adding a substantial number of bytes to the page, making it slower and requiring extra bandwidth. Of course the ViewState is controllable, much like the dinosaurs in Jurassic Park.

Not only is the ViewState gone, but “mystery” generated HTML is also gone. You have strict control over the HTML. This gives you great power, but with great power comes great responsibility. Use it wisely, and you will have elegant XHTML output with no surprises. You need to really know your HTML, which in today’s web world is a prerequisite anyway.

PRO – Faster server-side

It’s hard to get any real performance data about MVC, but it’s been suggested that it’s potentially 8000 times faster. Supposedly it’s due to less processing since it simply processes a “template” instead of having to build a complicated control tree. Even if it’s twice as fast, or even marginally faster, that would be significant for popular sites, or give at least a slight boost to smaller sites.

PRO – Simplified model for multiple related views

One thing that I found much easier to do with MVC was to have multiple versions of a page that displayed the same data, but in a slightly different format. For example, on my RSS package tracking website, you can look at your tracking information in a full-featured desktop browser, a mobile browser, or an RSS reader. The data being displayed is always the same, but the actual rendered output was different. If I later want to make an iPhone specific version for example, I would simply make a new view, and use an existing controller action.

PRO – Unit testable

One of the biggest challenges with WebForms was that testing was difficult. Not only was the actual output not easy to test, but the code-behind would tend to be a place that would contain important code that would never get unit tested. With both MVC and WebForms, it’s best to keep your logic away from the page, but it’s not always easy or ideal. MVC makes it simple to unit test the logic that is specific to a page. To do so, you simply test the actions in your controllers, which are regular, easy to test classes.

CON – Difficult to convert an existing site

MVC is not only a framework in this case, but a style. It is possible to convert specific pages as needed, but the cost is high. The problem is that MVC is radically different, so the benefit of converting probably isn’t worth it for most of your existing pages.

If you decide to convert your site to MVC, you may also run into issues trying to maintain existing page addresses. The specific issue I’ve ran into is that routes cannot have a trailing slash. If you want to maintain existing URL’s that have trailing slashes, there is no way to have the built-in routing generate URL’s with a trailing slash. You may end up losing one of the big advantages that MVC has to offer.

CON – Not best for SEO out of the box

I’ve mentioned some of the SEO issues before, and all but the trailing slash issue have a reasonable workaround. The routing engine likes to allow multiple addresses to render the same page, instead of enforcing a single address for each page. Luckily, as Scott Hanselman mentions, you can use a URL rewrite engine to bend it to your will. I highly recommend spending some time writing intelligent rules that perform the necessary 301 redirects, because you don’t want to take chances with SEO (Search Engine Optimization).

CON – Challenges if you’re not running IIS7

It’s clear that the last couple of versions of IIS have been major improvements over their predecessors. IIS7 takes .NET integration to an entirely new level. There is already a good page that covers the challenges you’ll face if you’re not running IIS6. I’ll just list them here for brevity:

  • .NET needs to handle all page requests to ensure that the MVC pages will be processed. This leads to bad performance of static files.
  • HTTP Compression through IIS6 doesn’t work, because the MVC pages are dynamic.
  • The homepage gives a 404 when hosted on the root of a domain.


If I needed to build a new site from scratch, and was able to use IIS7, it would be extremely likely that I would choose ASP.NET MVC. It’s a joy to work with (possibly because it’s “new”), and just makes sense. If I needed to work with an existing site, I would certainly have to consider the pro’s and con’s I mentioned above. ASP.NET MVC gives us an amazing new tool in our huge Microsoft toolbox.



RESTful Authentication

How to handle authentication in a RESTful Client-Server architecture is a matter of debate.

Commonly, it can be achieved, in the SOA over HTTP world via:

  • HTTP basic auth over HTTPS;
  • Cookies and session management;
  • Query Authentication with additional signature parameters.

You’ll have to adapt, or even better mix those techniques, to match your software architecture at best.

Each authentication scheme has its own PROs and CONs, depending on the purpose of your security policy and software architecture.

HTTP basic auth over HTTPS

This first solution, based on the standard HTTPS protocol, is used by most web services.

It’s easy to implement, available by default on all browsers, but has some known draw-backs, like the awful authentication window displayed on the Browser, which will persist (there is no LogOut-like feature here), some server-side additional CPU consumption, and the fact that the user-name and password are transmitted (over HTTPS) into the Server (it should be more secure to let the password stay only on the client side, during keyboard entry, and be stored as secure hash on the Server).

Session via Cookies

To be honest, a session managed on the Server is not truly Stateless.

One possibility could be to maintain all data within the cookie content. And, by design, the cookie is handled on the Server side (Client in fact does even not try to interpret this cookie data: it just hands it back to the server on each successive request). But this cookie data is application state data, so the client should manage it, not the server, in a pure Stateless world.

The cookie technique itself is HTTP-linked, so it’s not truly RESTful, which should be protocol-independent, IMHO.

Query Authentication

Query Authentication consists in signing each RESTful request via some additional parameters on the URI. See this reference article.

It was defined as such in this article:

All REST queries must be authenticated by signing the query parameters sorted in lower-case, alphabetical order using the private credential as the signing token. Signing should occur before URL encoding the query string.

This technique is perhaps the more compatible with a Stateless architecture, and can also be implemented with a light session management (using in-memory sessions instead of DB persistence).

Server-side data caching can be always available. For instance, in our framework, we cache the responses at the SQL level, not at the URI level. So adding this extra parameter doesn’t break the cache mechanism.

It’s worth concluding that REST is not only HTTP-based, even if, in practice, it’s mostly implemented over HTTP. REST can use other communication layers. So a RESTful authentication is not just a synonym of HTTP authentication, whatever Google answers. It should even not use the HTTP mechanism at all, but shall be abstracted from the communication layer.

See this article for some details about RESTful authentication in a client-server ORM, based on JSON and REST. Since we allow communication not only over HTTP/1.1, but also named pipes or GDI messages (locally), we tried to implement a truly RESTful authentication pattern, and not rely on HTTP specificity (like header or cookies).


LINQ and Deferred Execution

LINQ and Deferred Execution

This post covers one of the most important and frequently misunderstood LINQ features. Understanding deferred execution is a rite of passage that LINQ developers must undergo before they can hope to harness the full power of this technology. The contents of this post assumes an intermediate understanding of LINQ.