如何在AngularJS中正确清理?

时间:2015-05-16 14:20:23

标签: javascript angularjs

我有AngularJS应用程序(见下文),它使用指令从外部库创建自定义块。我想在块被加载时调用Building.destroyBlock()(不是所有块都需要)。我在考虑$scope.$watch()。是否有更好的方式,如ng-destroy或其他什么?



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:5)

我怀疑范围$destroy事件是您之后的事。

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