在以下情况下如何使用包含。目的是在html(部分)文件中使用标记,而不是在模板中(在指令内)定义标记。
我没有在指令中定义模板,而是尝试使用包含在内的内容。我还将Angular更新为1.2.0.rc2。更新时间:http://jsfiddle.net/aZx7B/2/
低于错误
TypeError:对象[object Object]的属性’$ transclude’不是函数
码:
module.directive("tree", function($compile) { return { restrict: "E", transclude: true, scope: {family: '='}, template: '<ul>' + '<li ng-transclude></li>' + '<li ng-repeat="child in family.children">' + '<tree family="child"></tree>' + '</li>' + '</ul>', compile: function(tElement, tAttr) { var contents = tElement.contents().remove(); var compiledContents; return function(scope, iElement, iAttr) { if(!compiledContents) { compiledContents = $compile(contents); } compiledContents(scope, function(clone, scope) { iElement.append(clone); }); }; } }; }); <div ng-app="myapp"> <div ng-controller="TreeCtrl"> <tree family="family"> <p>{{ family.name }}</p> </tree> </div> </div>
在David的建议下,进行了一些更改。http://jsfiddle.net/aZx7B/3/ 现在,它会打印,父级。变化,family-> treeFamily虽然没有用
family
treeFamily
您还需要在模板中输出族的名称:http : //jsfiddle.net/roadprophet/DsvX6/
module.directive("tree", function($compile) { return { restrict: "E", transclude: true, scope: {family: '='}, template: '<ul>' + '<li ng-transclude></li>' + '<li ng-repeat="child in family.children">' + '<tree family="child">{{family.name}}</tree>' + '</li>' + '</ul>', compile: function(tElement, tAttr, transclude) { var contents = tElement.contents().remove(); var compiledContents; return function(scope, iElement, iAttr) { if(!compiledContents) { compiledContents = $compile(contents, transclude); } compiledContents(scope, function(clone, scope) { iElement.append(clone); }); }; } }; });
编辑
您也可以通过执行以下操作来简化操作:http : //jsfiddle.net/roadprophet/DsvX6/2/
<div ng-app="myapp"> <div ng-controller="TreeCtrl"> <tree family="treeFamily"> </tree> </div> </div> module.directive("tree", function($compile) { return { restrict: "E", transclude: true, scope: {family: '='}, template: '<ul>' + '<li ng-transclude></li>' + '<p>{{ family.name }}</p>' + '<li ng-repeat="child in family.children">' + '<tree family="child"></tree>' + '</li>' + '</ul>', compile: function(tElement, tAttr, transclude) { var contents = tElement.contents().remove(); var compiledContents; return function(scope, iElement, iAttr) { if(!compiledContents) { compiledContents = $compile(contents, transclude); } compiledContents(scope, function(clone, scope) { iElement.append(clone); }); }; } }; });
编辑 虽然问题的根源相同。没有模板传递给内部树指令。 http://jsfiddle.net/roadprophet/DsvX6/3/
<div ng-app="myapp"> <div ng-controller="TreeCtrl"> <tree family="treeFamily"> <p>{{ family.name }}</p> </tree> </div> </div> template: '<ul>' + '<li ng-transclude></li>' + '<li ng-repeat="child in family.children">' + '<tree family="child"><div ng-transclude></div></tree>' + '</li>' + '</ul>'