I need to conditionally use a child directive inside a parent directive.
I'm using $compile
to compile a template for a child directive in parent directive's link
function, and the child directive has its own isolated scope.
The problem is that an ng-click
on the child directive is invoked in the parent scope when the child directive's element is clicked.
Here is an SSCCE:
var app = angular.module("test", []);
app.directive("parentDirective", function($compile) {
return {
restrict: "EA",
scope: {},
link: function(scope, element, attrs) {
element.append('!');
scope.foo = function() {
alert('parent foo');
};
var childTemplate = "<div child-directive ng-click='foo()'>Child directive</div>";
element.append($compile(childTemplate)(scope));
}
};
});
app.directive("childDirective", function() {
return {
restrict: "EA",
scope: {},
link: function(scope, element, attrs) {
scope.foo = function() {
alert('child foo!');
};
element.append('!');
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="test">
<div parent-directive>Parent directive</div>
</div>
The ng-click=foo()
should invoke foo
from the child scope, however it's invoking the parent foo
. If you click Child directive!
div you get Parent foo
alert.
Why is that so and how can I make it work as expected?
scope:true
to get the parent scope – redconservatory