tuchk4
tuchk4

Reputation: 2350

AngularJS: rootScope in directives scopes

For example I have directive

App.directive('module', function($compile)
{   
    return  {

        replace     : true,         
        restrict    : 'E',
        link: function(scope, iElement, iAttrs)
        {   
            scope.localName = '1';
        },

        template : '<div> {{ name }} - {{ localName }}</div>',  
    }       
});

At application run function:

App.run(function($rootScope, $location)
{
    $rootScope.name = "test";
}

So in this way directive's scope will be same for all directives but this scope will have access to $rootScope:

<module></module> 
<module></module>

https://i.sstatic.net/QF8wM.png

But if I will make an isolated scope:

App.directive('module', function()
{   
    return  {

        replace     : true,         
        restrict    : 'E',
        link: function(scope, iElement, iAttrs)
        {   
            scope.localName = '1';
        },

        template : '<div> {{ name }} - {{ localName }}</div>',
            scope : {}  
    }       
});

Scopes will be different, but they will be have access to $rootScope.

https://i.sstatic.net/XITHr.png

So I need to isolate the scope of each directive but I need this scope to have access to $rootScope.

Can you help me please?

Upvotes: 4

Views: 11298

Answers (1)

Eduard Gamonal
Eduard Gamonal

Reputation: 8031

scope: true

not isolated, not shared, but a new prototipically inherited scope per directive instance.

http://jsfiddle.net/4LAjf/1

You can log the id of the scope with console.log(scope.$id). With scope: {} you'll get, for example, 003 and 004. With scope: false (or nothing), the scope is shared, e.g. both have 002. With scope:true they have different id's but can read $rootScope.

In the live example you can see the scope ID in your local variable localName. I named the dummy directive mydir instead of module. It just looks weird naming module a directive.

More about AngularJS scopes

Upvotes: 4

Related Questions