繁体   English   中英

ngRepeat结合其他指令

[英]ngRepeat combined with other directive

我有一个严重的问题。 必须使用一些组合数据实现表视图。 我必须在表行中显示一些数据,后续行必须是有关此行的一些详细信息。 更重要的是,用户应该能够隐藏点击该行的详细信息。

例如,模型是某人的姓名。 他有孩子,他们的名字必须在他的名字后面的下一行显示。 根据我的模型,子名称存储在他们父亲的属性中,这是一个与自身类似的对象数组。 孩子不能有其他孩子。

问题是我无法在ngRepeat循环的单次运行中处理多个表行。 我也尝试添加另一个指令,它没有帮助,因为ng-repeat的transclude被设置为'element'。 之后我尝试修改ng-repeat指令,几乎达到了结果,但我不得不在指令编译函数的中间创建元素。 这是一个非常糟糕的主意,因为代码变得非常脏并且难以支持。

这就是我修改ng-repeat指令的方法:(只显示改变的部分)

if (!last) {
    linker(childScope, function(clone){
        var el = clone; //angular.element(template);
        cursor.after(el);
        if (!childScope.item.innerHidden) {
            for (var i = 0; i < childScope.item.innerItems.length; i++) {
                var innerItem = childScope.item.innerItems[i];
                console.log(innerItem);
                var elem = angular.element('<tr><td>' + innerItem.value1 + '</td><td>' +
                    innerItem.value2 + '</td></tr>');
                el.after(elem);
                el = elem;
            }
        }
        last = {
            scope: childScope,
            element: (cursor = el),
            index: index
        };
        nextOrder.push(value, last);
    });
}

我能做什么? 我在想一些可能是孩子和父母的html标签,这可能吗? 我可以对它应用ng-repeat并管理其中的表行。 还是有其他有趣的可能性吗?

我会将外部ng-repeat放在tbody标签上。 一个表可以包含多个tbody,它允许您有多个行共享同一个对象。 对于隐藏子行,有多种选择。 在我的例子中,我选择了一个简单的。 它可能不是最好的,因为它使用视图的标志来对模型进行轮询,但它会让你对如何做到这一点有一个很好的了解。

让我们说这是你的模型:

  $scope.family = [
    {
      name : 'Bob',
      age : 34,
      children : [
        {
          name: 'Robert',
          age: 12
        },
        {
          name: 'Paul',
          age: 10
        }
        ],
        show:true
    },
        {
      name : 'Mike',
      age : 23,
      childrens : [],
      show:true
    }
  ]

你会注意到show属性。 它被用于视图行隐藏技巧......正如我所说,你应该找到一个更好的方法来做到这一点。

要显示数据,请使用此表:

  <table>
    <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
    </tr>
    </thead>
    <tbody ng-repeat="person in family">
      <tr ng-click="showChildren(person)">
        <td>{{person.name}}</td>
        <td>{{person.age}}</td>
      </tr>
      <tr class="child" ng-show="person.show" ng-repeat="child in person.children">
        <td>{{child.name}}</td>
        <td>{{child.name}}</td>
      </tr>
    </tbody>
  </table>

您可能会注意到第一个tr上的ng-click和第二个tr上的ng-show。 这就是隐藏嵌套行的神奇之处。 只需在控制器中添加此方法即可使用!

  $scope.showChildren  = function(person){
    person.show = !person.show;
  }

无论如何......检查这个plunker ......这是一个有效的例子。 更容易理解!

http://plnkr.co/edit/fO7LWN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM