What is the behavior of Scope in AngularJS Directives?
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
- 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.
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)
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