在AngularJS中的ng-repeat指令中动态显示模板?

Bri*_*nga 11 angularjs

我试图根据当前项目动态显示ng-repeat指令中的几个模板之一.

我的JSON数据如下所示:

data: {
    groups: [
        {
            name: "Group 1",                
            sections: [
                { name: "Section A" },
                { name: "Section B" }
            ]
        },
        {
            name: "Group 2",                
            sections: [
                { name: "Section A" },
                { name: "Section B" }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我的目标是动态呈现数据树,每个组包含多个部分.这些组都将具有相同的模板,但每个部分应具有自己的模板,基于名称字段.

假设顶级HTML是:

<div ng-repeat="group in groups">
    {{ group.name }}
    <div ng-repeat="section in sections">
        <!-- Dynamic section template used -->
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

理想情况下,每个部分还需要有自己的作用域数据和与之关联的控制器.我有幸用Knockout构建这种类型的系统,但我正在尝试理解Angular的做事方式.

Jas*_*den 33

你可以这样做:

<div ng-repeat="group in groups">
    {{ group.name }}
    <div ng-repeat="section in sections" ng-include="getIncludeFile(section)">
        <!-- Dynamic section template used -->
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

$scope.getIncludeFile = function(section) {
    // Make this more dynamic, but you get the idea
    switch (section) {
        case "Section A":
            return 'partials/sectiona.html';
        case "Section B":
            return 'partials/sectionb.html';
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你的sectiona.html看起来像这样(要有一个特定于该文件的控制器):

<div ng-controller="SectionAController">
    <!-- HTML in here, and can bind straight to your SectionAController -->
</div>
Run Code Online (Sandbox Code Playgroud)