我需要有条件地在父指令中使用子指令。
我使用$compile
为父指令的link
函数中的子指令编译模板,并且子指令具有其自己的隔离范围。
问题是当child指令的元素被单击时,子指令中的ng-click
在父范围中被调用。
这里是一个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>
的ng-click=foo()
应该从孩子的范围援引foo
,但它的调用父foo
。如果您点击Child directive!
div,您会收到Parent foo
警报。
为什么如此以及如何使其按预期工作?
您需要使'''范围:true'''来获得父范围 – redconservatory