【问题标题】:AngularJS : Creating a directive that repeats a transcluded templateAngularJS:创建一个重复嵌入模板的指令
【发布时间】:2013-08-13 21:19:20
【问题描述】:

我有一种情况,我想创建一个指令,该指令接受一组项目并将它们拆分为可变数量的列,并用构成列的元素包装它们。在花了几个小时尝试各种事情之后,我很难过如何构建它。以下是我想如何使用这个指令:

<columnize columnCount="3" collection="items">
   <div>{{item.Name}}</div> <!-- this is the repeated part -->
</columnize>

该指令将接收两个输入,columnCount 和 collection。该指令在内部获取集合并将其拆分为具有所需列数的嵌套数组,每个列都有该列的项目。结果数组将如下所示:

$scope.columns = [
   [{Name: "Item1"}, {Name: "Item2"}, {Name: "Item3"}],
   [{Name: "Item4"}, {Name: "Item5"}, {Name: "Item6"}],
   [{Name: "Item7"}, {Name: "Item8"}]
];

然后我想使用类似这样的模板输出列块:

<div class="row-fluid">
    <div class="column" ng-repeat="column in columns">
        <span ng-repeat="item in column">
            <span ng-transclude></span>
        </span>
    </div>
</div>

问题在于我似乎无法让嵌入工作,因为它在 ngRepeat 中重复。我猜我需要克隆内容并以某种方式手动将它们插入到这个模板中,但我似乎找不到任何好的例子。我发现这看起来像是我想做的,只是没有嵌套的中继器:

http://liamkaufman.com/blog/2013/05/13/understanding-angularjs-directives-part1-ng-repeat-and-compile/

我希望有比这更简单的方法。有什么想法可以做到这一点吗?

【问题讨论】:

  • 你能创建一个 jsfiddle 吗?
  • 我可以,但它不起作用。抛出各种错误。我会看看我能做些什么。
  • 我会为你创建一个。但是你需要展示columnize是如何实现的

标签: templates angularjs angularjs-directive angularjs-ng-repeat


【解决方案1】:

http://plnkr.co/edit/j5wpTScJXoMMrIyXyASE?p=preview

我会这样做。 请记住,您肯定需要 CSS 来设置列布局样式。

app.directive('columnize', function() {
  return {
    restrict: 'E',
    scope: {
      collection: '=',
      columnCount: '='
    },
    transclude: true,
    template: '<div><div class="column" ng-repeat="col in cols">' + 
      '<div ng-repeat="item in col" ng-transclude></div>' +
      '</div></div>',
    link: function( scope ) {
      var partition = function partition( size, items ) {
        if ( items.length === 0 ) { return []; }
        return ([items.slice( 0, size )]).concat( partition( size, items.slice( size )));
      };
      var columnize = function() {
        if ( !scope.columnCount ) { return; }
        scope.cols = partition( scope.columnCount, scope.collection );
      };
      scope.$watch('columnCount', columnize );
      scope.$watch('collection', columnize );
    }
  };
});

【讨论】:

  • 谢谢,效果好多了。我的错误是试图在嵌套的 ng-repeat 的孩子上使用 transclude。伟大的工作。
  • 我采纳了你的想法并修复了我自己的指令,但我没有面临在同一元素上使用 ng-repeat 和表达式的新问题。请参阅我刚刚发布的关于此的问题:stackoverflow.com/questions/18237106/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
相关资源
最近更新 更多