Angular: rowGenerator directive
http://angularjs.org/
by mrajcok
HTML
<div ng-controller="MyCtrl">
<row-generator row-data=things col-count=3></row-generator>
<br><br>Test changing "things":
<br><a ng-click="removeThing2()">remove thing #2</a>
<br><a ng-click="addElement()">add a thing</a>
<br><a ng-click="changeThing1 ()">change thing #1</a> - won't work unless you change the directive to:
<code>scope.$watch('rowData', function(value){ ...}, true)</code>
</div>
JavaScript
var myApp = angular.module('myApp',[]);
myApp.directive('rowGenerator', function() {
var rowTemplate = '<div class="row">',
colTemplate = '<div class="span4">';
return {
restrict: 'E',
// use '=' for colCount instead of '@' so that we don't
// have to use attr.$observe() in the link function
scope: { rowData: '=', colCount: '='},
link: function(scope, element) {
// To save CPU time, we'll just watch the overall
// length of the rowData array for changes. You
// may need to watch more.
scope.$watch('rowData.length', function(value) {
var html = rowTemplate;
for(var i=0; i < scope.rowData.length; i++) {
html += colTemplate + scope.rowData[i].key + '</div>';
if (i % scope.colCount == scope.colCount - 1) {
html += '</div>' + rowTemplate;
}
}
html += '</div>';
// don't use replaceWith() as the $watch
// above will not work -- use html() instead
element.html(html);
})
}
}
});
function MyCtrl($scope) {
$scope.things = [
{key: 'one'},
{key: 'two'},
{key: 3},
{key: 4},
{key: 'five'},
{key: 'six'},
{key: 77},
{key: 8}
];
$scope.removeThing2 = function() {
$scope.things.splice(1, 1);
}
$scope.addElement = function() {
$scope.things.push({key: 'new thing'});
}
$scope.changeThing1 = function() {
$scope.things[0].key += ' more'
console.log($scope.things[0])
}
}