Exploring Angular’s “Controller as” Syntax and the vm Variable

Read full article on the Infragistics blog

Often, I hear developers ask “What is the ‘controller as’ syntax and how it is different from the $scope object approach of controller creation?” In this post we will learn about controller as syntax and compare it with the $scope object approach of controller creation.

In AngularJS 1.2, the “controller as” syntax was introduced, and made controller code creation more readable. Let’s see both approaches in action below:

Creating a controller using the $scope object

Usually we create a controller using the $scope object as shown in the listing below:

image

Above we are creating the AddController with three variables and one behaviour, using the $scope object controller and view, which talk to each other. The $scope object is used to pass data and behaviour to the view. It glues the view and controller together.

Essentially the $scope object performs the following tasks:

  1. Pass data from the controller to the view
  2. Pass behaviour from the controller to the view
  3. Glues the controller and view together
  4. The $scope object gets modified when a view changes and a view gets modified when the properties of the $scope object change

We attach properties to a $scope object to pass data and behaviour to the view. Before using the $scope object in the controller, we need to pass it in the controller function as dependencies.

Using the “controller as” syntax and vm

We can rewrite the above controller using the controller as syntax and the vm variable as shown in the listing below:

image

Read full article on the Infragistics blog

2 responses to “Exploring Angular’s “Controller as” Syntax and the vm Variable”

  1. […] scopes in AngularJS custom Directives and How to work with the Bootstrap DropDown in AngularJS and Exploring Angular’s “Controller as” Syntax and the vm Variable (Dhananjay […]

Leave a comment

Create a website or blog at WordPress.com