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 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,
        '<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,
        '<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 {
          firstName: '@dirFirstName',
          lastName: '=dirLastName',
          setNameMethod: '&dirUpdateNameMethod'
        '<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 ()
              newFirstName: scope.firstName,
              newLastName: scope.lastName


Post a Comment


ADFS (1) ADO .Net (2) Ajax (1) Angular (1) Angular Js (17) Angular2 (28) ASP .Net (14) Authentication (1) Azure (1) Breeze.js (1) C# (50) CD (1) CI (2) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DevOps (4) DI (4) Dotnet (22) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (50) NodeJS (7) RDLC (1) Report (1) SDLC (1) Sql Server (30) SSIS (3) SSO (1) SSRS (2) UI (1) WCF (13) Web Api (11) Web Service (1) XMl (1)

Dotnet Guru Archives