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:
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:
- Pass data from the controller to the view
- Pass behaviour from the controller to the view
- Glues the controller and view together
- 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:
Leave a Reply