This blog post is a 21 points cheat sheet on the AngularJS controller and the $scope object. These points can be used a quick notes while working with two important components of Angular app controller and the $scope object Notes on $scope object $scope is a glue between the view and the controller. It connects controller with the view. image

  1. $scope serve as the glue between controller and the view
  2. The $scope is the connection between the HTML and the view
  3. View and the model both have access of $scope
  4. In context of MVC , $scope can be seen as ViewModel
  5. $scope provides execution context for the DOM and the expression
  6. $scope provides an execution context in which DOM element is bound
  7. $scope are the source of the truth
  8. $scope gets modified when View changes and the view gets modified when $scope changes its value
  9. The $scope object is plain JavaScript object. We can add and remove property as required
  10. $scope holds data and functions from controller that should be displayed and get executed in view
  11. The $rootScope is eventual parent of all the $scope
  12. $rootScope is top most scope in on DOM element with ng-app directive
  13. In angular all the $scope are created with prototypal inheritance
  14. $scope has access to their parent scope
  15. $scope contains data and the functionality to be used to render the view
  16. For each controller creation and new $scope gets created
  17. It is ideal to contain the application logic in the controller and the data in the $scope of the controller.
  18. When $scope object is not needed in the view, scope will be cleaned up and destroyed
  19. Directives does not have their own scope but with some exceptions ng-controller and ng-repeat
  20. When angular starts running all the $scope are attached to the view
  21. $scope pass data and behavior to the view

Example: Adding property to $rootScope To add a property to $rootScope directly, pass $rootScope as parameter to the controller as shown below. However it is not advisable to add properties to $rootScope directly.

var myApp = angular.module('myApp', []);
myApp.controller('RootController', ['$rootScope', function ($rootScope) {

    $rootScope.name = "dj";

}]);

On the DOM added property of $rootScope can be rendered in the expression as shown below,

<div ng-controller="RootController">
<h1><strong>{{</strong>name<strong>}}</strong></h1>

</div>

Other way you can add property to the $rootScope object directly using the run method on the application module.

angular.module('myApp', [])
      .run(function ($rootScope) {
          $rootScope.name = &amp;quot;World&amp;quot;;
      });

To use this you don’t need controller to attach with the View and can be used in the application as shown below,

   <div ng-app="myApp">
        Hello {{name}}
    </div>


Notes on the controller

Controller adds behaviour and data to the $scope object. It gets created on the view using this ng-controller directive. Each controller has its own $scope object. image

  1. It’s a JavaScript constructor function that is used to augment the $scope object
  2. Controller takes $scope as parameter and attach data and behavior to this
  3. Controller is attached to DOM using the ng-controller directive
  4. Each controller has its own child $scope
  5. Controller set up the initial state of the $scope object
  6. Controller adds behavior to the $scope object
  7. Do not use Controller to manipulate DOM : It should only contain the business Login not the DOM manipulation
  8. Do not use controller to format the input
  9. Do not use controller to filter the output
  10. Do not use controller to share the code across the controller
  11. Never create the service instance inside the controller
  12. A Controller should mainly contain a simple business logic
  13. It should not try to do many things
  14. All the common functionality should go the service and the later service can be injected to the controller via dependencies
  15. Controller name starts with the capital letter and ends with the Controller
  16. Whenever new controller gets created on the page, angular pass a $scope object to it.
  17. Custom actions to be called from the view can be created as behavior of function in the controller augmenting to the $scope object
  18. Controller can be attached to different level of DOM hierarchy, hence its create hierarchy of the $scope.
  19. $scope in child controller can access and override data and behavior attached to $scope of the parent controller.
  20. Other directives or services to be used in the controller must be passed as parameter in the controller function constructor
  21. Controller should provide data and business logic to a particular View

Example: Creating a simple controller Let us create a simple controller with two functions as behavior and one data. Functions are either adding or subtracting 1 from the counter attached as property to $scope object.

var myApp = angular.module('myApp', []);
myApp.controller('mycontroller', ['$scope', function ($scope) {

    $scope.counter =0;
    $scope.add = function () { $scope.counter += 1;}
    $scope.sub = function () { $scope.counter -= 1; }
}]);

On the DOM controller can be used as shown below,


  <div ng-controller="mycontroller">
            <h1>{{counter}}</h1>
            <button class="btn btn-info" ng-click="add()">+</button>
            <button class="btn btn-danger" ng-click="sub()">-</button>
        </div>


When you use controller to another DOM element, a new instance of controller will get created.


<div class="container">

        <div ng-controller="ParentController">
            <h2>{{age}}</h2>
            <div ng-controller="ChildController">
                <h1>{{name}}</h1>
                <h2>{{age}}</h2>
                <h3>{{grade}}</h3>
            </div>
        </div>


On running the application you will find that both the div has different values for the $scope data. Example: $scope inheritance Let us create a module with two controller ParentControler and ChildController. As you see ChildController is overriding age property on the $scope object.

var myApp = angular.module('myApp', []);

myApp.controller('ParentController', ['$scope', function ($scope) {

    $scope.name = "dj";
    $scope.age = 32;

}]);
myApp.controller('ChildController', ['$scope', function ($scope) {

    $scope.age = 22;
    $scope.grade = &amp;quot;A+&amp;quot;;

}]);

In the view we have created ChildController inside the ParentController div. In the ChildController $scope, there is no property called name. So angular will traverse to the ParentController to find the value of the name property. Also you can notice that age property is overridden in the ChildController, so the div attached with the ChildController will render overridden value of the age property.


<div class="container">

        <div ng-controller="ParentController">
            <h2>{{age}}</h2>
            <div ng-controller="ChildController">
                <h1>{{name}}</h1>
                <h2>{{age}}</h2>
                <h3>{{grade}}</h3>
            </div>
        </div>


I hope, these 21 points about the $scope object and the controller should help you in working with AngularJS. Thanks for reading.

Advertisements

4 thoughts on “21 points cheat sheet on AngularJS controller and the $scope object

  1. DHANANJAY KUMAR sir thanks for this article, new to MVC learning it with AngularJS. I have a doubt about the points 10, 15, and 21, I think have the same meaning, if different please tell.

  2. These points can be used as quick notes when working with two important components of the Angular app Controller and the $scope object.

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