2015-05-14 62 views
1

我需要有条件地在父指令中使用子指令。

我使用$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警报。

为什么如此以及如何使其按预期工作?

+0

您需要使'''范围:true'''来获得父范围 – redconservatory

回答

1

这个问题是关于编制模板的范围。

检查这个PLUNKER

alert('init parent directive -1');会叫那么alert('init child directive');,最后alert('init parent directive-2');

,这意味着在line 20在plunker例如,父母向链路功能创建child-directive但该指令编译反对parent directive scopescope of the child directive,所以$compile()只能看到parent directive scope内不能看到关于child scope的任何内容。

如果您需要附加child scope那么您必须在child directive内编译它。或更好地在child directive中使用templatetemplateUrl

+0

我不明白,它在您更改子指令*时不起作用*隔离作用域,这是唯一需要的更改看起来,使它工作。 Parent指令仍在编译子指令。 –

0

var app = angular.module("test", []); 
 

 
app.directive("parentDirective", function($compile) { 
 
    return { 
 
    restrict: "EA", 
 
    template: "<div ng-click='foo()'>Parent directive!</div>", //You can use templateUrl as well 
 
    scope: {}, 
 
    link: function(scope, element, attrs) { 
 
     scope.foo = function() { 
 
     alert('parent foo'); 
 
     }; 
 
     var childTemplate = "<child-directive/>"; 
 
     element.append($compile(childTemplate)(scope)); 
 
    } 
 
    }; 
 
}); 
 

 
app.directive("childDirective", function() { 
 
    return { 
 
    restrict: "EA", 
 
    template: "<div ng-click='foo()'>Child directive!</div>", 
 
    scope: {}, 
 
    link: function(scope, element, attrs) { 
 
     scope.foo = function() { 
 
     alert('child foo!'); 
 
     }; 
 
    } 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script> 
 
<div ng-app="test"> 
 
    <parent-directive/> 
 
</div>

试试这个