Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

AngularJS Scope

What is scope in AngularJS?

Scope is a special JavaScript object that refers to the application model, you can consider this as a view model.

Scope objects Basic

Scope objects contain functionality and data that is used when rendering the view, reason Scopes are the source of truth for the application state.

Because of scope objects two-way automatic binding is possible in AngulaJS.

Scope features

1) Scopes provide APIs ($watch) to observe model changes.

2) Scopes provide APIs ($apply) to propagate model changes through the application as well as outside the system to other components associated (controllers, services, Angular event handlers).

3) Scopes can be nested in such a way that they can isolate functionality and model properties.

4)  Scopes provide context against which expressions are evaluated.

For example expression {{FirstName}}  is meaningless without scope which defines property “FirstName”.

Scope as Data-Model

Scope is the main communication gateway between application controller and the view.

During Template linking phase directive apply $watch expressions on scope then which allows the directive to render the updated value to the DOM.
<body>
 
    <div ng-app="myApp" ng-controller="MyController">
        Your name:
        <input type="text" ng-model="username">
        <button ng-click='DsiplayMessage()'>Show Message</button>
        <hr>
        {{WelcomeMessage}}
    </div>
    <script>
      
        angular.module('myApp', [])
        .controller('MyController', ['$scope', function ($scope) {
            $scope.username = 'Shourya Kendre';
 
            $scope.DisplayMessage = function () {
                $scope.WelcomeMessage = 'Welcome Mr. , '  + $scope.username + '!' + 'From , Team CodeChef4u';
            };
        }]);
    </script>
</body>

In the above example MyController assigns  “Shourya Kendre” to the username property of the scope. The scope then notifies the input of the assignment, which then renders the input with username pre-filled. This demonstrates how a controller can write data into the scope.

Similarly the controller can assign behavior to scope as seen by the DisplayMessage method, which is invoked when the user clicks on the button. The DisplayMessage method can read the username property and create a greeting property. This demonstrates that the properties on scope update automatically when they are bound to HTML input widgets

Scope Hierarchies:

Your angular app allows exactly only one root scope but you can add more child scopes in your application.

When new scopes are created they are added as children of their parent scope. This creates a tree structure which parallels the DOM where they're attached.

Example:

Root scope is available for entire application, in following example surname “Kendre” is in root scope and names are in child scope.

<div ng-app="myApp" >
        <!--root scope-->
        Surname: {{scopeName}}
        <div ng-controller="myCtrl">
            <ul>
                <!--child scopes-->
                Names <li ng-repeat="name in names">{{name}}</li>
            </ul>
        </div>
    </div>
 
    <script>
 
        var app = angular.module('myApp', []);
        app.run(function ($rootScope) {
            $rootScope.scopeName = 'Kendre';
        });
 
        app.controller('myCtrl', function ($scope) {
            $scope.names = ["Nagnath", "Aditya", "Ajay"];
        });
    </script>

 

Scope lifecycle:

Here I will try to explain sequence of actions performed with angularJS Scopes when we execute application.


1. Creation

When AngularApp page starts exaction during bootstrap process root scope is created by the $injector.

During template linking, some directives create new child scopes.

2. Watcher registration

During template linking, directives register watches on the scope. These watches will be used to propagate model values to the DOM.

3. Model mutation

For mutations to be properly observed, you should make them only within the scope.$apply(). Angular APIs do this implicitly, so no extra $apply call is needed when doing synchronous work in controllers, or asynchronous work with $http, $timeout or $interval services.

4. Mutation observation

At the end of $apply, Angular performs a $digest cycle on the root scope, which then propagates throughout all child scopes. During the $digest cycle, all $watched expressions or functions are checked for model mutation and if a mutation is detected, the $watch listener is called.

5. Scope destruction

This is concept like memory releasing or cleaning unused objects in classic C++ or C programming.

When child scopes are not required its responsibility of creater to destroy child scopes using

scope.$destroy() API.This will stop propagation of $digest calls into the child scope and allow for memory used by the child scope models to be reclaimed by the garbage collector.

Reference used:

Used angularjs.org developer guide docs.

Special thanks to aangularjs.org documentation team.

 

AngularJS Data Binding

Data binding is key advantage of AngularJS compared with other framework, here Data-binding is the automatic synchronization of data between the model and view components.

In angular model is source of application and view is projection of the model at all time, when the model changes, the view reflects the change, and vice versa.

Classic framework data binding and AngularJS data binding


AngularJS inbuilt directive used for data binding

ng-bind: Binds the vale to an HTML element.
ng-bind-template: Almost similar to the ng-bind directive but allows for multiple template.
ng-non-bindable: Declares a region of content for which data binding will be skipped.
ng-bind-html: Creates data bindings using the inner HTML property of an HTML element.
ng-model : allows a two-way data binding.

One way data binding

With one way data binding approach value is taken from model and inserted into an HTML element. There is no approach of update model from view.

Example:

Following example displays employee and employee project details taken from model.

<body>
    <div ng-app="myApp" ng-controller="EmployeeController">
    Id: {{Employee.id}}
    <br/>
    Name:<span ng-bind="Employee.name" ></span>
 
    <p>Designation: {{Employee.Designation}}</p>
         <ul>
            <li data-ng-repeat="myObject in Employee.Projects">id:{{myObject.id}} name:{{myObject.name}} Team Size:{{myObject.TeamSize}}</li>
        </ul>
    </div>
 
    <script>
        var app = angular.module('myApp', []);
        app.controller('EmployeeController', ['$scope'function ($scope) {
            $scope.Employee = {
                id: 1,
                name: 'Sankruti Kendre',
                Designation: 'Team Leader',
                Projects: [
                    { id: 1, name: 'E shop', TeamSize: 5 },
                    { id: 2, name: 'Employee Notifier', TeamSize: 3 },
                    { id: 3, name: 'CRM', TeamSize: 10 }
                ]
            };
        }]);
        </script>
</body>

Two way data Bindings

In two way data binding goes both ways, In simple language two-way data binding is when the model changes, the view reflects the change, and vice versa.

Example:

In the following example if the user changes the value inside the input field, the AngularJS property will also change its value.

 <body>
<div ng-app="myApp" ng-controller="myCtrl">
   Your Good Name: <input ng-model="name">
       Your good name is {{name}}
</div>
<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl'function ($scope) {
        $scope.name = "Nagnath Kendre";
    });
</script>
 
</body>

 

AngularJS Custom Directives

Introduction

In last post I explained in detail with example AjngularJS Directives and its use, in this post I Will explain how to create your own custom directive and use it.

AjngularJS built-in directives cover many different scenarios and inbuilt directives made your work easy.

Example

ng-repeat directives repeats html elements for each item in a collection, you can use this directive like classic programming  for loop logic on data collection.

Like this AjngularJS provided number of built-in directives those covers different scenarios, still it is possible to implement your own directives too.

How to create directive?

1. New Custom directives are created by using the .directive function.
2. Custom directive replaces for which element it is activated.
3. The type of a directive determines how the directive is activated.

Example:

In following example custom directive is created to display employee manger details, template and restrict properties are used in following custom directive.  

<body ng-app="myApp">
    <h2>AngularJS Sample Example</h2>
    <div ng-app="myApp" ng-controller="MyTestController">
        First Name: <input type="text" ng-model="FirstName"><br><br>
        Last Name: <input type="text" ng-model="LastName"><br>
        <br>
  
        Full Name:{{FirstName+" " + LastName}}
 
       <!--Manger Details custom directive activated using element-->
        <managerdetails></managerdetails>
    </div>
 
        <script>
            var app = angular.module('myApp', []);
 
            app.controller('MyTestController', function ($scope) {
                $scope.FirstName = "Shourya";
                $scope.LastName = "Kendre";
                $scope.Manager = {
                    Name: "Nagnath",
                    Location: "Pune"
                };
     
            });
 
            app.directive("managerdetails", function () {
                return {
                    restrict: 'EA',//E = element, A = attribute, C = class, M = comment
                    template: "Manager Name: {{Manager.Name}}<br /> Location: {{Manager.Location}}"
                };
            });
        </script>
</body>

Custom Directive properties

In following table all directive properties are explained in short

Property

Description

restrict

Decides where a directive can be used (as an element, attribute, CSS class, or comment).

scope

Used to create a new child scope or an isolate scope.

template

Defines the content that should be result of directive.

This include html elements, another directive, and data binding expressions.

templateUrl

Provides the path to the template that should be used by the directive.

controller

Used to define the controller that will be associated with the directive template.

link

Function used for DOM manipulation tasks.

 

Custom directives Types and its use  

You can implement the following types of directives:

=> Element directives
=> Attribute directives
=> CSS class directives
=> Comment directives

1. An element directive is activated when AngularJS finds a matching HTML element in the HTML template.

Example:

   <!--Manger Details custom directive activated using element-->
   <managerdetails></managerdetails>

2. An attribute directive is activated when AngularJS finds a matching HTML element attribute.

Example:

  <!--Manger Details custom directive activated using div attribute-->
    <div managerdetails></div>

 3. A CSS class directive is activated when AngularJS finds a matching CSS Class.

Example:

Note: This code with above example only works after removing existing restriction on custom directive.

<!--Manger Details custom directive activated using div css class-->
    <div class="managerdetails"></div>

4. A comment directive is activated when AngularJS finds a matching HTML comment.

custom detective Activated using comment 

        <!-- directive:managerdetails -->

Restrictions:

You can restrict custom directives to only be accessed and used by some of the methods.

The restrict field is used to set if the directive should be activated by a matching HTML element, or an element attribute.
E” restrict field value (Element)
By setting restrict to E you specify that only HTML elements named div should activate the directive.
“A” restrict field value (Attribute)
By setting restrict to A you specify that only HTML attributes named div should activate the directive.
“C” restrict field value (Class)
By setting restrict to C you specify that only HTML css Class named div should activate the directive.
 “M” restrict field value (Comment)
By setting restrict to M you specify that only HTML comment should activate the directive.

Example:

You can also use a value of AC which will match both HTML element names and css class names.

<script>
   var app =angular.module('myApp', []);
   app.directive("managerdetails", function () {
   return {
                    restrict: 'AC',//E = element, A = attribute, C = class, M = comment
                    template: "Manager Name: {{Manager.Name}}<br /> Location: {{Manager.Location}}"
        };
       });
</script>

 

By default the value is EA, meaning that both Element names and attribute names can access and use the directive.