Skip to content

Instantly share code, notes, and snippets.

@OzieWest
Created June 24, 2014 19:03
Show Gist options
  • Select an option

  • Save OzieWest/519cb87cb432108066ab to your computer and use it in GitHub Desktop.

Select an option

Save OzieWest/519cb87cb432108066ab to your computer and use it in GitHub Desktop.
Invoke func after ngRepeat
app.directive("repeatComplete", function( $rootScope ) {
// уникальный ID (ведь может быть несколько вложенных ng-repeat)
var uuid = 0;
// компилируем DOM узел до того как он будет залинкован директивой ng-repeat
function compile( tElement, tAttributes ) {
// получаем уникальный ID
var id = ++uuid;
// присваиваем ID элементу
tElement.attr( "repeat-complete-id", id );
// удаляем значение директивы с элемента (оно больше не требуется)
tElement.removeAttr( "repeat-complete" );
// следим за Expression чтобы вызвать нашу функцию только один раз
var completeExpression = tAttributes.repeatComplete;
// получаем родительский жлемент (который содержит в себе список)
// искать будет только внутри этого лемента, зачем напрягать весь документ?
var parent = tElement.parent();
// забираем родительский Scope. Подбираемся к ngRepeat как можно ближе,
// чтобы иметь возможность быстро отвязаться (unbind) при уничтожении (destroy) родительского элемента
var parentScope = ( parent.scope() || $rootScope );
var unbindWatcher = parentScope.$watch(function() {
console.info( "Digest running." );
var lastItem = parent.children( "*[ repeat-complete-id = '" + id + "' ]:last" );
if ( ! lastItem.length ) {
return;
}
var itemScope = lastItem.scope();
if ( itemScope.$last ) {
unbindWatcher();
itemScope.$eval( completeExpression );
}
});
}
return({
compile: compile,
priority: 1001,
restrict: "A"
});
});
<li
ng-repeat="enemy in enemies"
repeat-complete="doSomething($index)">
{{ enemy.name }}
</li>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment