It is clear that when I assign a controller to an element, the element along with its children can access the controller's scope.
However, it is surprising that when I include a directive with an isolated scope on an element (as an attribute), I would anticipate that the element and its children could utilize the isolated scope, but they are unable to do so.
HTML:
<body ng-app="testMod" ng-controller="ParentController">
<div id="div1" ng-controller="MyController">
<a href="#" ng-click="doit()">MyController</a>
</div>
<div id="div2" my-directive>
<a href="#" ng-click="doit()">MyDirective</a>
</div>
</body>
JS:
(function() {
angular
.module('testMod', [])
.controller('ParentController', ['$scope', function($scope) {
$scope.doit = function() {
console.log('ParentController scope')
}
}])
.directive('myDirective', [function() {
return {
scope: {},
restrict: 'A',
controller: 'MyController'
};
}])
.controller('MyController', ['$scope', function($scope) {
$scope.doit = function() {
console.log("MyController scope");
};
}]);
})();
Upon clicking the link within #div1
, the output is MyController scope
, as expected.
Contrary to my expectations, upon clicking the link within #div2
, which has an isolated scope due to the directive, the output is ParentController scope
.
Which elements exactly have access to the isolated scope? To what does it apply? Is there a way to allow the children of div[my-directive]
to access it somehow?
Transclusion does not offer a solution in this scenario; I specifically want the children of div[my-directive]
to utilize the directive's isolated scope instead of the parent scope. Although I need a link
function for DOM manipulation on the children, I essentially desire the same controller behavior from #div1
.