在 AngularJS 的 ng-repeat 指令中动态显示模板? [英] Dynamically displaying template in ng-repeat directive in AngularJS?

查看:19
本文介绍了在 AngularJS 的 ng-repeat 指令中动态显示模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据当前项目在 ng-repeat 指令中动态显示多个模板之一.

我的 JSON 数据如下所示:

数据:{组: [{名称:第1组",部分: [{名称:A部分"},{ 名称:B 部分"}]},{名称:第2组",部分: [{名称:A部分"},{ 名称:B 部分"}]}]}

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

假设顶级 HTML 是:

{{ 团队名字 }}<div ng-repeat="节中的节"><!-- 使用的动态部分模板-->

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

解决方案

你可以这样做:

{{ 团队名字 }}<div ng-repeat="section in section" ng-include="getIncludeFile(section)"><!-- 使用的动态部分模板-->

然后在您的控制器中:

$scope.getIncludeFile = function(section) {//让这更动态,但你明白了开关(部分){案例A部分":返回 '​​partials/sectiona.html';案例B部分":返回 '​​partials/sectionb.html';}}

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

<!-- HTML 在这里,并且可以直接绑定到您的 SectionAController -->

I am attempting to dynamically display one of several templates within an ng-repeat directive, based on the current item.

My JSON data looks like this:

data: {
    groups: [
        {
            name: "Group 1",                
            sections: [
                { name: "Section A" },
                { name: "Section B" }
            ]
        },
        {
            name: "Group 2",                
            sections: [
                { name: "Section A" },
                { name: "Section B" }
            ]
        }
    ]
}

My goal is to render the tree of data dynamically, with each group containing multiple sections. The groups will all have the same template, but each section should have its own template, based on the name field.

Assuming the top level HTML is:

<div ng-repeat="group in groups">
    {{ group.name }}
    <div ng-repeat="section in sections">
        <!-- Dynamic section template used -->
    </div>
</div>

Ideally, each section would also need to have its own scoped data and controller associated with it. I've had good luck building this type of system with Knockout but am trying to understand the Angular way of doing things.

解决方案

You could do something like this:

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

Then in your controller:

$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';
    }
}

Then your sectiona.html could look like this (to have a controller specific to that file):

<div ng-controller="SectionAController">
    <!-- HTML in here, and can bind straight to your SectionAController -->
</div>

这篇关于在 AngularJS 的 ng-repeat 指令中动态显示模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆