首页 文章

在角度指令中重复被转换的内容

提问于
浏览
1

我正在尝试在Angular中编写一个简单的树指令,它将嵌套项目,并在每个重复的项目中重复第一次调用指令中声明的已转换内容 .

我试过这个,

angular.module('angularTree',[])
    .directive('tree',['$compile',function($compile)
    {

        return {

            scope:{item:"="},
            transclude:true,
            template:"<div class='tree-item'><ng-transclude></ng-transclude>" +
                        "<div id='tree-content' class='tree-content'>" +
                            "<div ng-repeat='child in item.items'>" +
                                "<tree item='child'><ng-transclude></ng-transclude></tree>" +
                            "</div>" +
                        "</div>",
            link:function(scope,element,attrs)
            {

            }
        }


    }]);

它起到了一定的作用 . 它创建一个嵌套的树,包含已转换的内容 .

问题是重复的子指令中的范围总是指向声明的第一个项目 . 所以当我在我的控制器中有一个这样的变量时..

var item = {name:John, items:[{name:Tony},{name:Jill}]};

并将其传递给这样的指令

<tree item="item"></tree>

我得到一个嵌套的项目列表,但他们都说“约翰” .

我可以看到为什么会发生这种情况,因为第二种情况与第一种情况相同 .

我的问题是......我将如何重复子元素中的被转换内容,但是范围指向子对象而不是顶级节点?

我已经阅读并尝试使用$ compile和transclude函数,但我看不出任何方法来实现这一点 .

谢谢

1 回答

  • 1

    它应该像你拥有它一样工作 . 我想你只是混淆了物品和孩子 . 不能确定,因为你的代码没有显示输出名称的位置 .

    在ng-repeat循环中,child指的是item.items的给定,但item仍然与外部项相同 . 我提供了一个工作示例,评论中的输出:

    angular.module('myApp', [])
    .directive('tree',[function($compile) {
        return {
          scope:{
            item: "="
          },
          transclude:true,
          template: "{{item.name}}" + // John, Tony, Jill
                    "<div class='tree-item'><ng-transclude></ng-transclude>" +
                      "<div id='tree-content' class='tree-content'>" +
                        "<div ng-repeat='child in item.items'>" +
                          "{{item.name}}" + // John, John
                          "{{child.name}}" + // Tony, Jill
                          "<tree item='child'><ng-transclude></ng-transclude></tree>" +
                        "</div>" +
                      "</div>",
          link: function(scope,element,attrs) {}
        }
      }]
    )
    .controller('treeCtrl', ['$scope', function($scope) {
      $scope.item = {
        name: 'John', 
        items: [
          {name: 'Tony'},
          {name: 'Jill'}
        ]
      };
    }])
    

相关问题