Thursday, 6 July 2017

Scopes in AngularJS Custom Directives

In this post we will learn about different kinds of scopes in AngularJS custom directives. First we’ll start with a high level introduction of directives and then focus on scopes.

Directives

Directives are one of the most important components of AngularJS 1.X, and have the following purposes:
1.       Gives special meaning to the existing element
2.       Creates a new element
3.       Manipulates the DOM

Beyond ng-app, ng-controller, and ng-repeat, there are plenty of built-in directives that come with AngularJS, including:
·         ng-maxlength
·         ng-minlength
·         ng-pattern
·         ng-required
·         ng-submit
·         ng-blur
·         ng-change
·         ng-checked
·         ng-click
·         ng-mouse
·         ng-bind
·         ng-href
·         ng-init
·         ng-model
·         ng-src
·         ng-style
·         ng-app
·         ng-controller
·         ng-disabled
·         ng-cloak
·         ng-hide
·         ng-if
·         ng-repeat
·         ng-show
·         ng-switch
·         ng-view

Mainly, directives perform either of the following tasks:
·         Manipulate DOM
·         Iterate through data
·         Handle events
·         Modify CSS
·         Validate data
·         Data Binding

Even though there are many built-in directives provided by the Angular team, there are times when you might need to create your own custom directives. A custom directive can be created either as an element, attribute, comment or class. In this post, a very simple custom directive can be created as shown in the listing below:


MyApp.directive('helloWorld', function () {
    return {
        template: "Hello IG"
    };
});

While creating custom directives, it’s important to remember:

• The directive name must be in the camel case;
• On the view, the directive can be used by separating the camel case name by using a dash, colon, underscore, or a combination of these.

Scopes in Custom Directives

Scopes enter the scene when we pass data to custom directives. There are three types of scopes:

1.       Shared scope
2.       Inherited scope
3.       Isolated scope

Shared scope
This type is requested when scope is false in the definition object or when scope is not specified (false is the default value of the property).
Shared scope simply means that the directive works with the same scope that is already available for the DOM node where the directive appears without creating a new one.


// 1. Shared scope (scope: false)
  .directive("nghSharedScopeDir", function ()
  {
    return {
      scope: false,
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}'
    };
  })

Inherited scope
This type is requested when scope is true in the definition object.
A new scope is created for our directive, but it inherits all the properties of the parent scope through JavaScript's prototypal inheritance: when the directive accesses a property on it's new scope, the property is first searched on the current scope and if it's found then it's value is returned, otherwise, if it's not found, the same property name is searched in the parent scope and that value is returned (the search traverses all the parents until the property is found or until there are no more parents); if a value is assigned to a property on the new directive's scope and the same property already exists in the parent, accessing the property value directly in the new scope will in fact override the parent's property value and any change to the property in the parent will not be propagated anymore to the child scope.


// 2. Inherited scope (scope: true)
  .directive("nghInheritedScopeDir", function ()
  {
    return {
      scope: true,
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}'
    };
  })

Isolated Scope
In Isolated scope, the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.
1.       Data can be passed as a string using the @ string literal
2.       Data can be passed as an object using the = string literal
3.       Data can be passed as a function using  the & string literal

// 3. Isolated scope (scope: {})
  .directive("nghIsolatedScopeDir", function ()
  {
    return {
      scope:
        {
          firstName: '@dirFirstName',
          lastName: '=dirLastName',
          setNameMethod: '&dirUpdateNameMethod'
        },
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<button ng-click="execSetNameMethod()">Set name on external scope</button><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}',
      link: function (scope, element, attrs)
      {
        scope.execSetNameMethod = function ()
        {
          scope.setNameMethod(
            {
              newFirstName: scope.firstName,
              newLastName: scope.lastName
            });
        };
      }
    };
  })


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives