fgonzalez
fgonzalez

Reputation: 3887

AngularJS Directives isolated scopes

I am learning about directives in AngularJS and I came across this code:

var app = angular.module('app', []);
//creating custom directive syntax
app.directive("myDir", function () {
return {
        restrict: "E", //define directive type like E = element, A = attribute, C =
        class, M = comment
        scope: { //create a new child scope or an isolate scope
     title: '@' //@ reads the attribute value,
 //= provides two-way bindi

My questions are:

According to the code, the attribute 'scope' apparently is used to create either a child scope, or an isolated scope. How do we then differentiate if we want the scope for this directive to be isolated or not? If I only want to have an scope child but not isolated how would I do?

Isolated means that the isolated scope that we are creating cannot access the variables from the parent scope, right?

A parent scope by default cannot access the variables from the child, but a child can access the variables of the parent if this one is not isolated, am I right?

And last question, if we define an attribute 'controller' to specify a controller for this directive, this directive will have by default the scope of the controller?

Thanks!!

Upvotes: 0

Views: 73

Answers (1)

Cirdec
Cirdec

Reputation: 24166

Set scope: true to get a new child scope that isn't isolated.

From the angular-js docs:

scope

If set to true, then a new scope will be created for this directive. 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.

If set to {} (object hash), then a new "isolate" scope is created. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

Upvotes: 1

Related Questions