gpt4 book ai didi

javascript - 如何在 AngularJS 中正确清理?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:33:32 24 4
gpt4 key购买 nike

我有 AngularJS 应用程序(见下文),它使用指令从外部库创建自定义 block 。我想在 block 重新加载时调用 Building.destroyBlock()(不需要所有 block )。我在考虑 $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>

最佳答案

我怀疑范围 $destroy 事件就是您所追求的。

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

关于javascript - 如何在 AngularJS 中正确清理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30276787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com