How do I access a controllers scope after a transclusion?

97 views Asked by At

Correct me if I am wrong, but I think in the firstDirective scenario, I am unable to achieve the behavior of the secondDirective because it's creating a sibling scope; I am unable to access the template's controller's scope. I want the behavior of the secondDirective with the power of transclusion. Is there a way to achieve this? or am I attacking this problem the wrong way?

http://jsfiddle.net/3QRDt/68/

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

app.directive('firstDirective', function(){
    return {
        restrict: 'EA',
        replace: true,
        scope: true,
        transclude: true,
        template: '<div id="holder" data-ng-controller="MyController">{{shouldBeOpen}}<div ng-transclude></div><button data-ng-click="close()">Close</button></div>',
        link: function(scope, element) {
            scope.openDirective = function() {
                scope.open()
                alert("Hello from Directive")
            }
            scope.hello ='dad'            
        }
    };
})
.directive('secondDirective', function(){
    return {
        restrict: 'EA',
        replace: true,
        scope: true,
        transclude: true,
        template: '<div id="holder" data-ng-controller="MyController">{{shouldBeOpen}}<button data-ng-click="openDirective()">{{hello}} Open</button><button data-ng-click="close()">Close</button></div>',
        link: function(scope, element) {
            scope.openDirective = function() {
                scope.open()
                alert("Hello from Directive")
            }
            scope.hello ='dad'            

        }
    };
});;

app.controller('MyController', ['$scope', function($scope) {
    $scope.shouldBeOpen = false
    $scope.close = function() {
        $scope.shouldBeOpen = false
    }
    $scope.open = function() {
        $scope.shouldBeOpen = true
        alert("Hello from Controller")
    }
}]);
1

There are 1 answers

0
zs2020 On

You can use $$prevSibling to reference from the transcluded scope to the isolated scope created by the directive:

<button data-ng-click="$$prevSibling.openDirective()">{{hello}} Open</button>