Ruslanas Balčiūnas
Ruslanas Balčiūnas

Reputation: 7428

How to properly clean up in AngularJS?

I have AngularJS application (see below) which uses directive to create custom blocks from external library. I want to call Building.destroyBlock() when blocks are realoaded (not neccessary all of them). I was thinking about $scope.$watch(). Is there a better way like ng-destroy or something?

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.blocks = [
    {name: 'item #1', id: 1},
    {name: 'item #2', id: 2}
  ];
}).directive('externalBlock', function() {
  return {
    restrict: 'A',
    scope: {
      block: '=data'
    },
    link: function(scope, elm, attrs) {
      Building.addBlock(elm[0], scope.block);
    }
  }
});
<script src="https://code.angularjs.org/1.4.0-rc.2/angular.js"></script>
<script>
  // this comes from external library
  var Building = {
    blocks: [],
    addBlock: function(elm, block) {
      elm.innerHTML = block.name + ' [ready]';
      this.blocks[block.id] = block;
    },
    destroyBlock: function(id) {
      delete this.blocks[id];
    }
  }
</script>

<body ng-controller="MainCtrl" ng-app="app">
  <div ng-repeat="block in blocks" external-block data="block"></div>
  <!-- need to destroy unused block when this button is clicked -->
  <button ng-click="blocks = [{name: 'item #3', id: 3}]">Rebuild</button>
</body>

Upvotes: 5

Views: 2630

Answers (1)

Michal Charemza
Michal Charemza

Reputation: 27012

I suspect the scope $destroy event is what you're after.

link: function(scope, elm, attrs) {
  Building.addBlock(elm[0], scope.block);
  scope.$on('$destroy', function() {
    Building.destroyBlock(scope.block.id);
  });
}

Upvotes: 6

Related Questions