異なるタイプのアイテムの配列をレンダリングしたい (つまり、例 #1) 1 つのオブジェクト タイプに対して、存在する場合は子アイテムのツリーをレンダリングします。リンクとコンパイルの両方の方法を組み合わせて目的を達成する方法がわかりません。リンクからコンパイル段階に移動する方法がわかりません。
レンダリングする必要があるデータ モデルは次のとおりです。
- item1.type = 'type2'
- item2.type = 'type1'
- item3.type = 'ツリールート' item3.children = []; // ツリーを表すオブジェクトの配列
- item4.type = 'type2'
- item5.type = 'type1'
つまり、type1.template、type2.template、tree-root.template、tree-node.template があります。tree-root.template のレンダリングには、tree-node.template を使用した子の ng-repeat 再帰レンダリングが含まれます。
データ型に基づく動的テンプレート選択の例を次に示します: https://coderwall.com/p/mgtrkg - リンク関数を使用して正しいテンプレートを選択し、明示的にコンパイル関数を含めません。
angular.module('components', []). directive('tumblrPost', ['$compile', '$http', '$templateCache', function($compile, $http, $templateCache) { var getTemplate = function(contentType) { var templateLoader, baseUrl = '/templates/components/tumblr/', templateMap = { text: 'text.html', photo: 'photo.html', video: 'video.html', quote: 'quote.html', link: 'link.html', chat: 'chat.html', audio: 'audio.html', answer: 'answer.html' }; var templateUrl = baseUrl + templateMap[contentType]; templateLoader = $http.get(templateUrl, {cache: $templateCache}); return templateLoader; } var linker = function(scope, element, attrs) { var loader = getTemplate(scope.post.type); var promise = loader.success(function(html) { element.html(html); }).then(function (response) { element.replaceWith($compile(element.html())(scope)); }); } return { restrict: 'E', scope: { post:'=' }, link: linker }; }]);
このフィドルからのディレクティブでの再帰の例を次に示します: http://jsfiddle.net/n8dPm/ - ツリー全体をレンダリングするまでコンパイルを再帰的に呼び出し、リンク関数を省略します。
module.directive("tree", function($compile) { return { restrict: "E", scope: {family: '='}, template: '<p>{{ family.name }}</p>'+ '<ul>' + '<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); }); }; } }; });