Laurent Perrin
Laurent Perrin

Reputation: 14881

AngularJS : Scope not shared across directives

I have 2 directives on the same tag, <settings> and <modal>. settings provides a template, while modal creates an isolated scope:

jsfiddle

var app = angular.module('app', []);

app.directive('settings', function () {
    return {
        restrict: 'E',

        template: '<div>SETTINGS</div>',

        link: function (scope) {
            console.log('settings', scope.$id);
        }
    };
});

app.directive('modal', function () {
    return {
        restrict: 'A',

        scope: {},

        link: function (scope) {
            console.log('modal', scope.$id);
        }
    };
});

However, they do not end up sharing the same scope, as shown by the logs:

<settings modal="settings"></settings>

settings 002
modal 003 

Why is that ?

Upvotes: 0

Views: 92

Answers (3)

atondelier
atondelier

Reputation: 2434

Till version 1.2.0rc3, sibling directives were sharing the same isolated scope if created.

As of version 1.2.0, you cannot (and shouldn't) access the isolated scope from outside the contents compiled against this isolated scope. You shouldn't because you are creating a hidden relation between both directives. Better use directive's controller requirement via the require property, or share informations through injected services if singleton pattern can be applied to your use case.

It is finally deeply related to this other question about Directives with Isolated scope versions conflict

Upvotes: 1

app.directive('modal', function () {
    return {
        restrict: 'A',

        scope: false,

        link: function (scope) {
            console.log('modal', scope.$id);
        }
    };
});

scope: false will not create a new isolated scope. I you want to make two directives work between them use require a controller on the directive that way you can share data between them.

Upvotes: 0

doodeec
doodeec

Reputation: 2927

scope: {} option always creates an isolated scope for the directive, it doesn't care about other directives

Upvotes: 1

Related Questions