How to clean up properly in AngularJS?

I have an AngularJS application (see below) that uses a directive to create custom blocks from an external library. I want to call Building.destroyBlock()when blocks are loading (not necessarily all of them). I was thinking about $scope.$watch(). Is there a better way, like ng-destroyor something else?

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>
Run codeHide result
+4
source share
1 answer

I suspect that an $destroyarea event is what you need.

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

All Articles