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

16 浏览
0 Comments

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

我正试图在ng-repeat指令中根据当前项动态显示多个模板中的一个。\n我的JSON数据如下:\n数据:{\n groups: [\n {\n name: \"Group 1\",\n sections: [\n { name: \"Section A\" },\n { name: \"Section B\" }\n ]\n },\n {\n name: \"Group 2\",\n sections: [\n { name: \"Section A\" },\n { name: \"Section B\" }\n ]\n }\n ]\n}\n我的目标是动态渲染数据树,每个组包含多个部分。所有组都将有相同的模板,但每个部分应该有自己的模板,根据名称字段。\n假设顶层HTML是:\n{{ group.name }}\n\n理想情况下,每个部分还需要有自己的作用域数据和关联的控制器。我在使用Knockout构建这种类型的系统时获得了很好的运气,但我正在尝试理解Angular的做事方式。

0
0 Comments

动态显示模板在ng-repeat指令中的原因是为了支持在AngularJS中动态加载模板。这个问题的解决方法是使用两个指令将nginclude封装起来。下面是解决方法的代码示例:

HTML:


Controller:

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  var json = {data: {
    groups: [
        {
            name: "Group 1",                
            sections: [
                { name: "Section A" },
                { name: "Section B" }
            ]
        },
        {
            name: "Group 2",                
            sections: [
                { name: "Section A" },
                { name: "Section B" }
            ]
        }
    ]
  }};
  $scope.groups = json.data.groups;
}); 

Directive split into two:

app.directive('groupsControl', function(){
    return {
      restrict: 'E',
      replace: true,
      transclude: false,
      scope: { items:'=groupdata'},
      template: '
' + '{{ group.name }}' + '' + '
', // The linking function will add behavior to the template link: function(scope, element, attrs) { } } }).directive('sectionControl', function(){ return { restrict: 'E', replace: true, transclude: false, scope: { items:'=sections'}, template: '
' + '
', link: function(scope, element, attrs) { scope.getIncludeFile = function(section) { return section.name.toLowerCase().replace('section ','') + ".html"; } } } });

以上是解决该问题的原因和方法。希望能有人使用基于某些作用域数据的templateUrl函数来回答这个问题。

0
0 Comments

问题的出现原因是需要在ng-repeat指令中动态显示模板,根据不同的数据项加载不同的模板。解决方法是使用ng-include指令和一个getIncludeFile函数来获取需要加载的模板文件路径。根据不同的数据项,getIncludeFile函数返回相应的模板文件路径,然后通过ng-include指令将模板文件加载到页面中。每个模板文件可以使用独立的控制器,以便绑定特定于该文件的数据和逻辑。

具体的实现代码如下:

HTML模板:

{{ group.name }}

控制器:

$scope.getIncludeFile = function(section) {
    // 根据不同的section返回相应的模板文件路径
    switch (section) {
        case "Section A":
            return 'partials/sectiona.html';
        case "Section B":
            return 'partials/sectionb.html';
    }
}

sectiona.html模板文件:

这种方法适用于简单的需求,如果需求更复杂,可以考虑使用自定义指令来实现。对于需要将JSON数据项转换为链接列表,并且每个链接对应一个新页面的情况,可以使用相同的视图模板,但具有唯一的属性,如post-type。不需要数据库或管理员,只需为每个数据项创建一个新页面。

0