Skip to content

Instantly share code, notes, and snippets.

@mbostwick
Created February 7, 2017 16:15
Show Gist options
  • Save mbostwick/48f197d0761a7a17bc3e4fdc9221f2a4 to your computer and use it in GitHub Desktop.
Save mbostwick/48f197d0761a7a17bc3e4fdc9221f2a4 to your computer and use it in GitHub Desktop.
var decreaseNumberOfRepeatedElements = function (bothValues, newInt, ngRepeatScope) {
var limit = bothValues ? newInt : 0;
ngRepeatScope.last = ngRepeatScope.elems[limit];
for (var i = ngRepeatScope.elems.length - 1; i > limit; i -= 1) {
ngRepeatScope.elems[i].remove();
ngRepeatScope.elems.pop();
}
};
var increaseNumberOfRepeatedElements = function (newInt, ngRepeatScope, ngRepeatTransclude) {
var i = ngRepeatScope.elems.length - 1;
for (i; i < newInt; i += 1) {
var childScope = ngRepeatScope.$new();
childScope.$index = i;
ngRepeatTransclude(childScope, function (clone) {
ngRepeatScope.last.after(clone);
ngRepeatScope.last = clone;
ngRepeatScope.elems.push(clone);
});
}
};
var nEntriesChanged = function (ngRepeatTransclude, ngRepeatScope, $parse, newValue, oldValue) {
var newInt = parseInt(newValue)
, oldInt = parseInt(oldValue)
, bothValues = !isNaN(newInt) && !isNaN(oldInt)
if (isNaN(newInt) || (bothValues && newInt < oldInt)) {
decreaseNumberOfRepeatedElements(bothValues, newInt, ngRepeatScope);
}
else {
increaseNumberOfRepeatedElements(newInt, ngRepeatScope, ngRepeatTransclude);
}
};
app.directive('ngRepeatN', ['$parse', function ($parse) {
return {
restrict: 'A',
transclude: 'element',
replace: true,
scope: true,
link: function (scope, element, attrs, ctrl, $transclude) {
scope.last = element;// the element to insert after
scope.elems = [element];// list of elements in the repeater
var getter = $parse(attrs.ngRepeatN);// a getter function to resolve the parameter
scope.$watch(function () {
return parseInt(attrs.ngRepeatN) || getter(scope);
}, function (newValue, oldValue) { nEntriesChanged($transclude, scope, $parse, newValue, oldValue) });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment