Recently Robin Ward did a comparison between AngularJS and Ember (both the post and the comments are interesting read). One of the complaint that Robin had that AngularJS does not provide any specialized model class. As described in the blog

There is no standard Model base class, nor is there a component or interface in AngularJS that defines what a model is supposed to be.

What that means is that anything defined on $scope can acts as model, as this sample on the blog describes

For some (like me) this is the flexibility where as for others who want a more structural approach this is a nuisance.AngularJS does not even provide any definite guidelines around how the model should be actually designed to be effective with AngularJS

This leads to what we call as $scope pollution. We define multitude of properties on the $scope object and managing it becomes difficult.  Looking at the code one cannot tell what is the actual model and what properties are just to support UI logic.

Model Design - Convention

We have been using AngularJS for some time now and we have devised a convention which  has helped us to keep $scope pollution under control. Here is how we organize our model.
  • On the Controller scope we create a object viewModel. ViewModel according to us is a model which has been tailored to support a specific UI, helping in easing data binding.
  • We define a property model on either the controller scope or on the viewModel defined above. This model is something that is loaded from the server and updated back on edits.
This is how a sample controller looks 

So any controller defines only one or two property directly on the $scope and that's it !

What could be the advantage of this small convention? Many :)


To start with, anyone reading the code can know what the model is and what variable are just used to support AngularJS data binding (such variables are created on viewModel object).

Ease of passing model around

Any decent size angular app/page would consist of multiple partial views and directives working together to provide the necessary functionality. One of the challenge in such setup is how to keep partial views and directives as independent as possible.

For partial views (views loaded using ng-include) here is how we define our template and main view.

As you can see, any template that requires a model to work on, gets it through ng-init. Just looking at the ng-init assignment one can determine what does a partial template require. Passing model around to these sub views become easier. Each of these partials can have their own controller and create their own viewModel object.

For directive, this is what we can do

For directives it becomes easier for us to create isolated scope, which has great benefits in terms of re-usability.

As you can see in both cases dependencies are clearly defined and there is a single root object at all levels.