What is the behavior of Scope in AngularJS Directives?

What is the behavior of Scope in AngularJS Directives?

Triveni Team

3–5 minutes
Share on Social Media

    Get The Expert Advice To Grow Your Business Digitally
    Related Blogs
    What is distributed Lock Manager in C# and Redis
    Read More: What is distributed Lock Manager in C# and Redis
    5 best tips to become a skilled programmer
    Read More: 5 best tips to become a skilled programmer
    How to implement Scatter Gather In Masstransit C#
    Read More: How to implement Scatter Gather In Masstransit C#
    What is the life cycle of AngularJS?
    Read More: What is the life cycle of AngularJS?

    What is Directive?

    In any application, if we want some specific functionality which we need to reuse in application, then for this we need to develop set of codes it calls Directive.

    I am not going in detail of directive, I assume that you have sufficient knowledge of directive so, I am just focus on use of $scope into directive.

    Scopes in AngularJS

    $scope has a very important role in AngularJS, it works as a mediator between the Controller & View in an Angular. Each scope object created by controller or any other directive or service are inherited from rootscope.

    1. It is difficult to maintain over time (tightly Coupled)Over the time if Data Access class change its constructor at that time it break the Business Layer classes which are dependent on that class & it is hard to manage in every changes.

    2. Hard to Unit TestIt is hard to mock Data Access layer classes in unit test case of Business layer classes & make it complex.

    $scope into directive

    All directive have a scope associated with it. Directive use scope for accessing data & Methods inside the template and link function. Directive never create its own scope unless explicitly set. By default directive use their parent scope (from where it is called).

    We can change the default scope of the directive using scope property just like restrict, template, etc. the value of scope property define how scope of directive is behave. We can define scope property by 3 ways, following are different scenario of using scope inside directive:

    • The scope is not assigned or set as false
    • The scope set as true
    • Isolated scope
    Scope: false (Directive uses its parent scope)

    This is default value of scope in directive. When we declare scope: false in DDO (directive definition object) at that time the directive has the same scope as its parent controller.

    <div ng-app="test">
      <div ng-controller="parentController">
        <h2>Hey {{name}}</h2>
        <div>
        Change Form Header : <input type-="text" ng-model="name" />
        </div>
        <br/>
        <hr/>
        <div directive-with-true-scope></div>
      </div>
    </div>
    var app = angular.module("test", []);
    
    app.controller("parentController", function($scope) {
      $scope.name = "Hitesh";
    });
    app.directive("directiveWithTrueScope", function() {
      return {
        restrict: "A",
        scope: true,
        template: "<div>Your name is : {{name}}</div>" +
          "Change your name : <input type='text' ng-model='name' />"
      };
    });

    in above example if we change name in textbox it also change header value because of directive use parent controller scope so any changes inside directive are reflected in the controller scope (Parent scope) same as any change in controller also reflected in directive.

    Scope: true (Directive gets a new scope)

    When we declare scope: true in DDO at that time directive define its own scope. This new scope inherited from its parent controller scope. In this case scope binding flow is one direction only from parent to directive scope so any change in directive not reflected in parent scope but when we change parent scope it reflect in directive scope.

    <div ng-app="app">
        
        <div class="parent" ng-controller="MainCtrl">
            <div class="line">
                Name inside parent scope is:<input type="text" ng-model="name" />
        </div> 
            <div class="line">
                Last name inside parent scope is: 
                <input type="text" ng-model="lastName" />
            </div>
            <br/>
            <hr/>
            <div class="directive" my-directive
                name="{{name}}"
                last-name="lastName"
            ></div>
        </div>
    </div>
    var app = angular.module("app", []);
    
    app.controller("MainCtrl", function( $scope ){
        $scope.name = "Hitesh";
        $scope.lastName = "Jariwala";
    });
    
    app.directive("myDirective", function(){
        
        return {
            restrict: "EA",
            scope: {
                name: "@",
                lastName: "="
            },
            template: [
                "<div class='line'>",
                "Name using @ : <input type='text' ng-model='name' /><br/>",
                "</div><div class='line'>",
                "Last name using =: <input type='text' ng-model='lastName' /><br/></div>"].join("")    
        };
    });
    <div ng-app="app">
        
        <div class="parent" ng-controller="MainCtrl">
            <div class="line">
                Name inside parent scope is:<input type="text" ng-model="name" />
        </div> 
            <div class="line">
                Last name inside parent scope is: 
                <input type="text" ng-model="lastName" />
            </div>
            <br/>
            <hr/>
            <div class="directive" my-directive
                name="{{name}}"
                last-name="lastName"
            ></div>
        </div>
    </div>
    var app = angular.module("app", []);
    
    app.controller("MainCtrl", function( $scope ){
        $scope.name = "Hitesh";
        $scope.lastName = "Jariwala";
    });
    
    app.directive("myDirective", function(){
        
        return {
            restrict: "EA",
            scope: {
                name: "@",
                lastName: "="
            },
            template: [
                "<div class='line'>",
                "Name using @ : <input type='text' ng-model='name' /><br/>",
                "</div><div class='line'>",
                "Last name using =: <input type='text' ng-model='lastName' /><br/></div>"].join("")    
        };
    });

    In above example if we change name in header textbox then it reflect in directive scope but when we change in directive scope it not reflect in parent scope, if you want to reflect parent scope then you need to use $parent for that

    Scope: { } (Directive gets the isolated scope)

    When we declare scope: {} as a object in DDO then directive will create a new isolated scope. and scope is not inherited from parent scope. so if we want to access parent scope values then we need to declare as a scope property in DDO and that property assignee through directive attributes. In isolated scope we can define scope property by using three prefixes. These are @ : One way binding = : Two way binding , & : Method binding

    In above example if we change name in parent scope so its reflect in directive scope but if we change name in directive scope then it’s not reflect in parent scope due to one way binding, same as if we change last name in parent scope it reflect in directive scope and also if we change last name in directive scope then it reflect in parent scope due to two way binding. Same as we can also pass method of parent scope in directive scope and call from directive.

    Share on Social Media

      Get The Expert Advice To Grow Your Business Digitally
      Related Blogs
      How to Manage Error Handling and Logging in Node Js?
      Read More: How to Manage Error Handling and Logging in Node Js?
      RAG Generative ai feature img
      Enhancing Business Solutions with Retrieval-Augmented Generation and Generative AI
      Read More: Enhancing Business Solutions with Retrieval-Augmented Generation and Generative AI
      How to create and deploy Python API in Docker?
      Read More: How to create and deploy Python API in Docker?
      How to implement Scatter Gather In Masstransit C#
      Read More: How to implement Scatter Gather In Masstransit C#

      Stay ahead of the curve

      Get the latest insights, tutorials, and industry news delivered straight to your
      inbox. Join 10,000+ developers and tech leaders.

      Get In Touch