Skip to content

Instantly share code, notes, and snippets.

@btm1
Created September 28, 2013 20:17
Show Gist options
  • Save btm1/6746150 to your computer and use it in GitHub Desktop.
Save btm1/6746150 to your computer and use it in GitHub Desktop.
Set repeat is an AngularJS directive to iterate over a group of elements only one time and not add any watch listeners. It works the same way as ng-repeat and uses angular templating engine to render it's results. i.e. set-repeat="message in messages" where messages is an array of objects. This iteration will not update if the length of the arra…
angular.module('setRepeat',[]).directive('setRepeat', function () {
return {
transclude: 'element',
priority: 1000,
compile: compileFun
};
function compileFun(element, attrs, linker) {
var expression = attrs.setRepeat.split(' in ');
expression = {
child : expression[0],
property : expression[1]
};
return {
post: repeat
};
function repeat(scope, iele, iattrs /*, attr*/) {
var template = element[0].outerHTML;
var data = scope.$eval(expression.property);
addElements(data,scope,iele);
return;
function makeNewScope (index, expression, value, scope, collection) {
var childScope = scope.$new();
childScope[expression] = value;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === (collection.length - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
/**
*
* uncomment this if you want your children to keep listening for changes
*
**/
//childScope.$watch(function updateChildScopeItem(){
//childScope[expression] = value;
//});
return childScope;
}
function addElements (collection, scope, insPoint) {
var frag = document.createDocumentFragment();
var newElements = [], element, idx, childScope;
angular.forEach(data, function(v,i){
childScope = makeNewScope(i,expression.child,v,scope,collection);
element = linker(childScope, angular.noop);
newElements.push(element);
frag.appendChild(element[0]);
});
insPoint.after(frag);
return newElements;
}
}
}
});
@mjaworski-eab
Copy link

How could you force it to update when you want? Thanks for this code - very nicely done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment