2014-05-10 121 views
1

最近,我试图创建角的js递归树视图时碰到这个代码来其中testList是TestCtrl中的JSON对象数组,例如:角JS动态指令模板

$scope.testList = [ 
    {text: 'list item 1'}, 
    {text: 'list item 2', children: [ 
     {text: 'sub list item 1'}, 
     {text: 'sub list item 2'} 
    ]}, 
    {text: 'list item 3'} 
]; 

此代码运行良好,但temp收集指令和成员指令是硬编码的。我想知道是否有办法从html中获取集合和成员的模板。事情是这样的:

<div ng-controller="TestCtrl"> 
    <ul recurse="testList"> 
     <li>{{member.text}}</li> 
    </ul> 
</div> 

递归指令将是收集指令的替代,但模板递归才肯的<ul>元素它是连接到。

同样,会员指令的模板将从<ul>元素的子元素创建;在这种情况下为<li>元素。

这可能吗?

在此先感谢。

回答

1

在您的指令中,您可以使用transclude: true并在HTML中定义模板的一部分。指令模板可以使用ng-transclude来包含它。

想象一下这个模板:

<div my-list="testList"> 
    <b>{{item.text}}</b> 
</div> 

在你的指令,你可以使用transclusion控制列表项被呈现方式:

module.directive('myList', function() { 
    return { 
     restrict: 'A', 
     transclude: true, 
     replace: true, 
     scope: { 
      collection: '=myList' 
     }, 
     template: '<ul><li ng-repeat="item in collection"><div ng-transclude></div><ul><li ng-repeat="item in item.children"><div ng-transclude></li></ul></li></ul>' 
    }; 
}); 

Plunker

+0

感谢您的回答。这很有用,但并不完全符合我的要求。对于初学者来说,我提供的阵列在实践中可能会有很多层次;一个项目可以有子项目,他们可以有子项目等,这就是为什么我需要递归。此外,我正在尝试为html中的指令定义模板,以便我可以在许多位置使用该指令,但根据使用的元素更改呈现(或编译)的方式。 –