Chapter 7: Optimizing with the compile phase in ng-repeat
by rajeshpillai
HTML
<script src="https://code.angularjs.org/1.3.2/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Ctrl">
<button ng-click="items[2] = {}">Append</button>
<div ng-repeat="item in items">
<my-directive item="{{item}}-noindex">{{item}}</my-directive>
</div>
<hr />
<div ng-repeat="item in items track by $index">
<my-directive item="{{item}}-index">{{item}}</my-directive>
</div>
</div>
</div>
JavaScript
angular.module('myApp', [])
.controller('Ctrl', function ($scope) {
$scope.items = [1,2,3,4,5].map(function(val) {
return { num: val };
});
})
.directive('myDirective', function($log) {
return {
compile: function(el, attrs) {
$log.log('compiled', attrs.item);
return function link(scope, el, attrs) {
$log.log('linked', attrs.item);
// this will only be called in the repeater
// that does not use track by $index
scope.$on('$destroy', function() {
$log.log('destroyed');
})
};
}
};
});