1

AngularJS Module and Directives

angular.module('tabApp', [])

.directive('tabPanel', function () {
    return {
        scope: {
            isOpen: '='
        },
        template: '<div><div tab-content></div>',
        link: function (scope) {
            alert(scope.isOpen);
        }
    };
})

.directive('tabContent', function () {
    return {
        scope: {
            isOpen: '='
        },
        template: '<div>Content</div>',
        link: function (scope) {
            alert(scope.isOpen);
        }
    };
});

HTML

<div ng-app="tabApp">
    <div tab-panel is-open="true"></div>
</div>

I need the tabContent to access isOpen property in the tabPanel? What is the best and shortest way to achieve this?

shinorz0721
  • 145
  • 10
  • 1
    You should be creating controllers for your directives / components, then you can use the `require` property and the `ctrls` argument. See https://docs.angularjs.org/api/ng/service/$compile#-require- – Phil Feb 21 '17 at 03:26

2 Answers2

3

You just have to pass the is-open from the parent directive to child directive...

.directive('tabPanel', function () {
    return {
        scope: {
            isOpen: '='
        },
        template: '<div><div tab-content is-open="isOpen"></div>',
        //...
    };
})

Check this jsFiddle

The.Bear
  • 5,621
  • 2
  • 27
  • 33
1

change child directive definition to

.directive('tabContent', function () {
    return {
        scope: {
            isOpen: '='
        },
        template: '<div>Content</div>',
        link: function (scope, attr, element, tabApp) {
            alert(scope.isOpen);
        },
        require: '^tabApp'
    };

and then use link function to receive the tabApp, something similar to this

Community
  • 1
  • 1
harishr
  • 17,807
  • 9
  • 78
  • 125