var app = angular.module('demo3', []); app.controller('DemoCtrl', function($scope) { $scope.items = []; $scope.addItem = function() { $scope.items.push(Math.random()); } $scope.removeItem = function(index){ $scope.items.splice(index,1); } for (var i=0; i<3; i++) $scope.addItem(); }); app.directive('notifier', function() { // this directive receive arbitrarous announcer calls return { restrict: 'A', controller : function($scope,$element){ this.addElement = function(elmScope){ console.log('item added', elmScope); document.getElementById('log').innerHTML += 'item added: ' + elmScope.item + '<br>'; } this.removeElement = function(elmScope){ console.log('item removed', elmScope); document.getElementById('log').innerHTML += 'item removed: ' + elmScope.item + '<br>'; } } } }); app.directive('announcer', function() { // this directive announces creation/destruction to the parent notifier if any return { restrict: 'A', require : '?^notifier', link: function(scope,element,attrs,notifierCtrl) { if(!notifierCtrl){ return; } notifierCtrl.addElement(scope); scope.$on("$destroy",function(){ notifierCtrl.removeElement(scope); }); } } })
<h3>Custom transclude demo</h3> <div ng-controller="DemoCtrl"> <ul notifier > <li announcer ng-repeat="item in items"> {{ item }}<button ng-click="removeItem($index)">x</button> </li> </ul> <button ng-click="addItem()">add item</button> <div id="log"></div> </div>