0
削除ディレクティブの後のクラスのインスタンスがなぜ破壊しないのかを理解するのに、もっと時間を費やしました。私は次のコードを書いた。それを解決するのを手伝ってください。コードは以下の通りです。コンソールログの結果!クラスのディレクティブ "person"インスタンスがまだ削除されているのはなぜですか?
'use strict';
var app = angular.module('app', []);
app.controller('mainController', function($scope, Service) {
$scope.service = Service;
$scope.checkAll = function() {
$scope.service.triggerListener('update');
};
$scope.add = function() {
$scope.count.push({});
};
$scope.object = {
updateAll: function() {
console.log('Count of directive "person"');
}
};
$scope.removeElement = function() {
$scope.count.splice(0, 1);
};
$scope.count = [0, 1, 2, 3, 4];
});
app.service('Service', function() {
this.listeners = [];
this.addListeners = function (object, event, callback) {
if (!this.listeners.hasOwnProperty(event)) {
this.listeners[event] = [];
}
this.listeners[event].push(object[callback]);
};
this.triggerListener = function(event) {
if (this.listeners.hasOwnProperty(event)) {
for (var i = 0; i < this.listeners[event].length; i++) {
this.listeners[event][i]();
}
}
};
});
app.directive('person', function() {
var directive = {
restrict: 'E',
template: '<button id="{{vm.index}}">Person</button> ' +
'<button ng-click="vm.add(index)">add</button>' +
'<button ng-click="vm.removeElement(index)">Clear</button>',
scope: {
index: '=',
service: '=',
removeElement: '&',
object: '=',
add: '&'
},
controller: function() {
},
link: function (scope) {
scope.vm.service.addListeners(scope.vm.object, 'update', 'updateAll');
},
controllerAs: 'vm',
bindToController: true
};
return directive;
});
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="mainController">
<div ng-repeat="item in count">
<person add="add()" index="$index" service="service" object="object" remove-element="removeElement()" show="show()">{{$index}}</person>
</div>
<button ng-click="checkAll()">Count of "person" directive</button>
</body>
</html>
リスナーを追加するだけですが、リスナーは削除しないためです。 –
'removeElement()'メソッドはリスナーを削除しません。 dom要素または 'count'配列要素を削除することは、サービスの' listers'配列に格納されているものとは何の関係もありません – charlietfl