问题
I have a situation where I want to create a directive that takes an array of items and splits them into a variable number of columns, wrapping them with elements that make the columns. After spending hours upon hours of trying various things I am stumped as how to architect this. Here is how I want to use this directive:
<columnize columnCount="3" collection="items">
<div>{{item.Name}}</div> <!-- this is the repeated part -->
</columnize>
The directive will receive two inputs, columnCount and collection. The directive internally takes the collection and splits it up into a nested array with the desired number of columns, each with the the items for that column. The resulting array would appear something like this:
$scope.columns = [
[{Name: "Item1"}, {Name: "Item2"}, {Name: "Item3"}],
[{Name: "Item4"}, {Name: "Item5"}, {Name: "Item6"}],
[{Name: "Item7"}, {Name: "Item8"}]
];
I then want to output the column chunks using a template similar to this:
<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>
The problem with this is that I can't seem to get the transclusion to work since its being repeated inside a ngRepeat. I am guessing I need to clone the content and insert them somehow into this template manually, but I cant seem to find any good examples. I found this which kind of looks like what I want to do, just without the nested repeaters:
http://liamkaufman.com/blog/2013/05/13/understanding-angularjs-directives-part1-ng-repeat-and-compile/
I am hoping there is an easier way to do this than that. Any ideas how I can accomplish this?
回答1:
http://plnkr.co/edit/j5wpTScJXoMMrIyXyASE?p=preview
This is how I would do it. Keep in mind that you'll definitely need CSS to style column layout.
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 );
}
};
});
来源:https://stackoverflow.com/questions/18219417/angularjs-creating-a-directive-that-repeats-a-transcluded-template