What is Diff between scope and Isolate scope - angularjs

While implementing directive I came across isolate scope , I am having Confusion why we have to Use isolate scope instead of scope.

When using an isolated scope, the directive's scope does not prototypically inherit from its parent. The directive has no access to the parent scope. This gives you the highest encapsulation. You should use an isolated scope, whenever you're designing reusable components.

Directives have access to the parent scope by default. For example, the following directive relies on the parent scope to write out a user object’s name:
angular.module('myDirective').directive('sharedScope', function () {
return {
template: 'Name: {{user.name}}'
};
});
The problem with this code is that you need to have an information about the parent scope, thus if the parent scope changes? The directive will become not usable anymore. That's when isolated scope comes in handy. Therefore isolated scope is used whenever directive is designed to be reusable. These are some good blog post which explain in depth the topic
AngularJS Directives, Using Isolated Scope with Attributes
Angularjs Sticky Notes
Creating Custom AngularJS
directives

Related

Priority between custom and built-in directve

I am reading ng-book-r27.
There are some something i can't understand well.
About 'Scope Option' of The chapter 'Directives Explained'.
First confusion:
If multiple directives on an element provide an isolate scope, only
one new scope is applied. Root elements within the template of a
directive always get a new scope; thus, for those objects, scope is
set to true by default.
I think that mean other directives will use the isolate scope as theirs.
is that right?
Second confusion:
example of inherited scope
ng-init has higher priority than custom directive.
Why the expression of ng-init will use the scope of custom dirctive.
I find a recommendation from offical doc about ng-init:
This directive can be abused to add unnecessary amounts of logic into
your templates. There are only a few appropriate uses of ngInit, such
as for aliasing special properties of ngRepeat, as seen in the demo
below; and for injecting data via server side scripting. Besides these
few cases, you should use controllers rather than ngInit to initialize
values on a scope.
OK, I can ignore the strange behavior of second confusion.
I have not read the book ng-book, but as far as I know, the statement of your first confusion does not conform with the AngularJS documentation regarding inherited and isolated scopes within a directive.
The statement above is simply not possible, having multiple directives that each have their own isolated scope would produce a $compile:multidir error. Here is a DEMO.
.directive('elem1', function($rootScope) {
return {
restrict: 'A',
scope: {}
};
})
.directive('elem2', function() {
return {
restrict: 'A',
scope: {}
}
});
After scanning the AngularJS documentation, there is no supporting statement that validates the statement:
If multiple directives on an element provide an isolate scope, only
one new scope is applied.
The closest statement I see that is similar to the statement above is the scope: true option definition when creating directives:
true: A new child scope that prototypically inherits from its parent
will be created for the directive's element. If multiple directives on
the same element request a new scope, only one new scope is created.
The new scope rule does not apply for the root of the template since
the root of the template always gets a new scope.
The statement above suggests that when multiple directives with scope: true option (not an isolated scope) resides in a single element, it would create one scope and everything else is a shared scope. DEMO
.directive('elem1', function($rootScope) {
return {
restrict: 'A',
scope: true,
link: function(scope) {
console.log(scope.hello);
}
};
})
.directive('elem2', function() {
return {
restrict: 'A',
scope: true,
link: function(scope) {
scope.hello = 'world';
console.log(scope.hello);
}
}
});
You would notice that both directives logs 'world', this obviously supports the statement above.
If you read more in the $compile scope AngularJS documentation, you would see that:
In general it's possible to apply more than one directive to one
element, but there might be limitations depending on the type of scope
required by the directives. The following points will help explain
these limitations. For simplicity only two directives are taken into
account, but it is also applicable for several directives:
no scope + no scope => Two directives which don't require their own scope will use their parent's scope
child scope + no scope => Both directives will share one single child scope
child scope + child scope => Both directives will share one single child scope
isolated scope + no scope => The isolated directive will use it's own created isolated scope. The other directive will use its parent's scope
isolated scope + child scope => Won't work! Only one scope can be related to one element. Therefore these directives cannot be applied to the same element.
isolated scope + isolated scope => Won't work! Only one scope can be related to one element. Therefore these directives cannot be applied to the same element.
Perhaps you're having problems identifying the difference between prototypically inherted scopes and isolated scopes. You might want to read the $rootScope.Scope $new() method, the isolate parameter definition.
First question:
I think that mean other directives will use the isolate scope as
theirs. is that right?
The answer is an absolute no, in reference towards multiple directives with isolated scope, it would produce the $copile:multidir error.
For your second question:
ng-init has higher priority than custom directive. Why the expression
of ng-init will use the scope of custom directive?
As for directives that do not have isolated scopes or directives that don't prototypically inherit from their parent scope, you can directly associate those directives as having a scope property definition with a falsey scope value:
falsy: No scope will be created for the directive. The directive will
use its parent's scope
If a directive is bound to an element with a scope of its own then it simply uses the scope of that element, otherwise it seeks all the scope instances within the scope chain until it reaches the $rootScope.

Scope in Angularjs

I was trying to understand scope in angularjs.
Say while registering a directive in angularjs if we dont provide any scope as the property of the object, what is the scope of the object then?
For example consider the following code:-
app.directive("kid", function() {
return {
restrict: "E",
template: '<input type="text" ng-model="chore"> {{chore}}'
};
});
Now say if i have 2 elements in my html:-
<kid></kid>
<kid></kid>
So how do above end up sharing the same scope? I am not able to find convincing answer yet.
Yes, As you didn't declared any scope option of directive, it will share the same scope.
Here is Demo Plunkr
Now come to the point, what is scope object?
scope object in Angular is nothing having context information and that will available on html, can also be utilized to provide two way binding. Basically scope is binded with some controller.
When things comes to directive scope, if you didn't mention scope property inside directive, that means directive shares the scope of the controller where the directive element has been placed.
To make them treated as a different scope for each directive you could create an an directive with an isolated scope, which can be defined using scope: {} inside a directive, when you define a scope: {} inside a directive, it creates an isolated child scope which is not prototypically inherited from the parent scope using $scope.$new(true) method.
Plunkr with isolated scope
Your question is about scope inheritance and isolate scope.
If you do declare a scope property on a directive object then the directive has its own isolate scope.
If you don't declare a scope property on your directive object the directive inherits the scope of the scope it was instantiated in.
So with your definition of the kid directive that doesn't declare an isolate scope the kid directives in the code example below both inherit the scope of the controller that they are instantiated in.
<div ng-controller="myCtrl">
<kid></kid>
<kid></kid>
</div>
Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.
Scope characteristics
Scopes provide APIs ($watch) toenter image description here observe model mutations.
Scopes provide APIs ($apply) to propagate any model changes through
the system into the view from outside of the “Angular realm”
(controllers, services, Angular event handlers).
Scopes provide context against which expressions are evaluated.
For example {{username}} expression is meaningless, unless it is evaluated against a specific scope which defines the username property.Scope is the glue between application controller and the view.

When does angularjs create new scopes

angularJS seems to create new scopes, in that there are parent scope, child scope, and sibling scope.
What determines when a new scope is created? For example, if I use ng-inspector to view the scopes present, there is the $rootScope, and also other scopes, but it is not obvious to me what the other scopes correspond to, nor is it clear to me when these other scopes are created/destroyed. I believe they are created/destroyed because the $id changes. Changes occur if I navigate around and press forwards/back.
Angular creates new scope for every instantiated controller on that part of DOM.
Angular also creates scope for every directive (except scope:false, that means for directives with isolated scope, and scope:true). A scope is also created for built in directives such as ng-repeat where it creates scope for every repeated item.
Also when you use ng-if directive it can remove and add parts of the DOM and when it adds it all the controllers and directives will add their scopes again.
Angular's scope tree pretty much will mirror the dom tree. Directives can create new scope. Not just your directives, but also built in Angular directives like ng-if. It's a bit of an in depth topic...
Here is a blog post that explains things more in depth.
Hope that helps!

Why use scope in directive and how to use it?

I see so many examples https://docs.angularjs.org/guide/directive and What is the difference between & vs # and = in angularJS but even I don't understand the scope principe in a directive. It's very confusing to use this. Some examples make use of scope:true; and
scope: {
sourceObj: '=',
lookupSource: '#',
searchRes: '&',
disableSearch: ''
}
What is using a boolean value (scope:true;) doing exactly?
scope:true
If you set scope:true (instead of scope: { ... }) then prototypical inheritance will be used for that directive.
This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.
example
scope:false (default)
the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.
example
scope: {......}
the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope.
Notice, even the parent scope has a name “Harry”, the textbox inside directive is blank. This is because of the new Isolated scope doesn’t know anything about its parent scope.
example
Notice, even the parent scope has a name “Harry”, the textbox inside directive is blank. This is because of the new Isolated scope doesn’t know anything about its parent scope.
NOTE: I dont want now post diferences between scope properties (#,&,=) , it will be another lesson
from this source
It's all about whether or not you want to create an isolated (new) scope for your directive or you want to inherit the from the parent scope. Specifying scope: true is essentially the same as scope: {}. It just says, 'hey, I want my own private scope here'. The only difference between those two is that you can use the object notation to specify your own scope properties to use in your directive.

AngularJS combining the use of two custom directives with shared scope

I have two different custom directives, both having an isolated scope. Is there a way to use both directives on the same element without getting:
Error: Multiple directives [...] asking for isolated scope on ...
I thought that they would share a common scope by doing so but it appears it won't (as I get this error)...
Thanks
Tom
OK, I've workarounded that issue by using the same controller for my both directives, allowing them to share the scope different from the parent scope...
I'm still interested in any suggestion on that subject.
There's a summary of how directive scopes can be combined in the reference to the $compile method.
The main points are that isolate scopes are never shared, and that an element can have at most one scope attached to it. If your directives use a child scope instead, then it will be shared between both directives.
no scope + no scope => Two directives which don't require their own scope will use their parent's scope
child scope + no scope => Both directives will share one single child scope
child scope + child scope => Both directives will share one single child scope
isolated scope + no scope => The isolated directive will use it's own created isolated scope. The other directive will use its parent's
scope
isolated scope + child scope => Won't work! Only one scope can be related to one element. Therefore these directives cannot be applied
to the same element.
isolated scope + isolated scope => Won't work! Only one scope can be related to one element. Therefore these directives cannot be applied
to the same element.
Well, I think Angular gives you the choice between working with a parent scope and communicating between directives.
You can achieve the latter one by adding an interface in the "master" directive by adding a controller function which the "slave" directive consumes. The slave explicates the dependency via require: '^masterDirective' and can use its interface in the link function.
See the official explanation with a nice example: https://docs.angularjs.org/guide/directive#creating-directives-that-communicate

Resources