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

Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s