Angular Directives and its Scope

Directive, what is the purpose of having a directive in our code?

For instance, I want a Vehicle to travel and I have all the parts required for that like tiers, bolts, body and other needed material, so I would just assemble them and use it whenever I need. Else it is a nightmare to assemble the car each time I need to go out.  Similarly, I have a functionality bound within a directive and reuse it wherever I need it in my application like  Angular builtin directives ng-bind, ng-init, ng-app and many more.

Angular also allows to create our own directives with any name we like. So we can have a custom directive with a scope variable, however it is optional to define scope inside a directive. If we skip mentioning scope, it gets default with false. There are mainly 4 ways to define scope of the directive-

a) scope: false

It just shares the scope with controller, that is when a change made in directive, it reflects in controller and other directives as well.

Example: Close friend, who shares everything.

b) scope: true

It inherits the scope from controller acting as its child, that is a change in directive, do not reflect in controller or other directives.

Example: greedy friend, who do not want to give his stuff to others but would take from them.

c) scope: {}

This is known as isolated scope, which completely isolates scope from its parent directive, and do not inherit anything from parent and do not share anything out as well.

Example: Real quite friend, who do not take or give from others.

d) scope: { var1: ‘=’,    var2: ‘&’,   var3: ‘@’,   callVar4: ‘&dirVar4’ } 

This is the best practice of all, which helps us to choose what variables should be visible to outer world and what not. In this case, only the variables or functions that are mentioned within { } are allowed to communicate with controller and changes for these variables made in directive will reflect in controller and other directives as well.

Example: Work Friends, who shares stuff that are important to work but not random unnecessary stuff.

var1: ‘=’ – It allows two way binding for scope variables,

var2:’@’  – It is for string variables

var3:’&’ – for accessing methods that are in controller

callVar4:’&dirVar4′ –  same as above method but for giving new name for method in controller.

This is very vast subject to discuss but above details give a precise knowledge required to dive into the details of directives and scopes.

Leave a comment