MVVM architectural pattern with AngularJS

AngulaJS is a framework for writing Single Page applications (SPA). It is just one of many JavaScript frameworks for developing SPA, but it is widely used. One of the reasons is that AngularJS is, as authors say, MVW framework (Model – View – Whatever).

What is MVW? There are several most popular architectural patterns for developing of web apps. MVC (Model – View – Controller) is well-known for long time and is main pattern for developing server-side code for web apps. MVVM pattern is relatively new, and it is evolving with applications for mobile devices, but has moved to SPA also.

So, AngularJS is designed to be used with whatever architecture pattern. It gives freedom to a developer to decide what pattern to use. However, AngularJS is primarily MVC framework, as it brings views and controllers out of the box.

Let’s take a look at basic controller declaration:

We are grabbing myApp module, and creating myController by passing factory function. This function receives $scope parameter that is injected when the function is called. This represents property bag which can hold everything we need in View to render and function. Because of this, it can be called Model in MVC architecture.

If you are coming from world of mobile devices, and you are familiar with MVVM pattern, you can easily use AngularJS and keep working as you are used to.

The first thing that comes out is that we don’t need Controller but ViewModel. View should be bound to VM and not to $scope.

There is one simple solution which can make a difference. We can consider using $scope as VM, but it can be extended with properties and functions only within controller. So we can use controller just to inject single item in the scope, and it should be a ViewModel:

ViewModel parameter will be automatically injected if it is declared within the app module. Sample ViewModel can look like this:

In this sample, ViewModel has array of data and refresh function.

Once it is injected into $scope, view can be bound to it (by accessing vm variable in the scope):

One Comment

Leave A Comment