将数据绑定到父指令中存在的自定义子指令
binding the data to custom child directives which are exist in the parent derictives
此程序仅给出 parent-directive
的输出。
我该怎么做才能显示 child-directive
指令?
这是我的程序
<div ng-app="Myapp">
<parent-directive>
<!--parent directive -->
<child-directive>
<!--child directive -->
</child-directive>
</parent-directive>
</div>
这是 angularjs 创建父指令和子指令函数的代码
var app = angular.module("Myapp", []);
app.directive("parentDirective", function() {
return {
restrict: "E",
template: "<p>Hello this is parent directive</p>",
};
});
app.directive("childDirective", function() {
return {
restrict: "E",
template: "<p>Hello this is child directive</p>",
};
});
这不起作用,因为您的父指令的模板覆盖了您在 <parent-directive></parent-directive>
之间声明的 html。为避免这种情况,您必须在父指令中允许包含:
app.directive("parentDirective",function(){
return {
restrict:"E",
transclude: true,
template:"<p>Hello this is parent directive</p><div ng-transclude></div>"
};
});
然后在您在父指令模板中声明 ng-transclude 的任何位置插入子指令。
可以在这里找到一个很好的解释:
https://thinkster.io/egghead/transclusion-basics
此程序仅给出 parent-directive
的输出。
我该怎么做才能显示 child-directive
指令?
这是我的程序
<div ng-app="Myapp">
<parent-directive>
<!--parent directive -->
<child-directive>
<!--child directive -->
</child-directive>
</parent-directive>
</div>
这是 angularjs 创建父指令和子指令函数的代码
var app = angular.module("Myapp", []);
app.directive("parentDirective", function() {
return {
restrict: "E",
template: "<p>Hello this is parent directive</p>",
};
});
app.directive("childDirective", function() {
return {
restrict: "E",
template: "<p>Hello this is child directive</p>",
};
});
这不起作用,因为您的父指令的模板覆盖了您在 <parent-directive></parent-directive>
之间声明的 html。为避免这种情况,您必须在父指令中允许包含:
app.directive("parentDirective",function(){
return {
restrict:"E",
transclude: true,
template:"<p>Hello this is parent directive</p><div ng-transclude></div>"
};
});
然后在您在父指令模板中声明 ng-transclude 的任何位置插入子指令。 可以在这里找到一个很好的解释: https://thinkster.io/egghead/transclusion-basics