I've noticed what seems to be a bug for me, but is probably more me misusing the $compile service in AngularJS : I have a directive called "dynamic" that compiles angularjs code and shows it into a div. The code that I compile in that case contains ng-controllers and those controllers are listening on events. The problem is that apparently controllers aren't "dead" after being replaced, because controllers that should be vanished still react to events (like $routeChangeSuccess or any other event).
Here is a working plunkr that shows the problem.
Let's see an example code of my problem :
The directive I'm using :
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, element, attrs) {
scope.$watch(attrs.dynamic, function(html) {
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
The main controller, followed by the controllers that I include:
app.controller('TestCtrl', function($scope) {
$scope.dynamicContent = "Default content";
$scope.firstButton = function() {
$scope.dynamicContent = "<div ng-controller='FirstCtrl'>The div from first button</div>";
}
$scope.secondButton = function() {
$scope.dynamicContent = "<div ng-controller='SecondCtrl'>The div from second button</div>";
}
$scope.checkButton = function() {
$scope.$broadcast('checkEvent');
}
});
app.controller('FirstCtrl', function($scope) {
$scope.$on('checkEvent', function() {
alert(1);
});
});
app.controller('SecondCtrl', function($scope) {
$scope.$on('checkEvent', function() {
alert(2);
});
});
Now if I call firstButton() then secondButton() then checkButton(), instead of receiving only the alert(2), I receive two alerts. If I hit buttons 1/2/1/2/1/2/1/2 it's going to show me as many alerts as buttons I've clicked.
What am I doing wrong here ?
Thanks, hilnius
dynamicdirective does whatng-includedoes ... except thatng-include(my assumption) is probably using $scope.$destroy() to get rid of scopes created by the dynamic templates it has loaded.