dimanche 4 janvier 2015

angular Send event to directive

I'd like to send an event from my view controller to the directive. I did the following: (I'd like to program a general alert-box which can receives alerts via event of the outer view controller).


In my view template I added the directive:


html template of view:



<alert-box></alert-box>


in the view controller:



$scope.$broadcast('add-alert', {type: 'danger', msg: message});


My directive:



.directive(
'alert-box', [function () {
return {
restrict: 'E',
templateUrl: '/directives/alert-box.html',
scope: false,
controller: [
"$scope",
function ($scope) {

$scope.alerts = [];

$scope.$on('add-alert', function(event, arg) {
$scope.addAlert(arg);
});

$scope.addAlert = function (alert) {
$scope.alerts = [];
$scope.alerts.push(alert);
};

$scope.closeAlert = function (index) {
$scope.alerts.splice(index, 1);
};
}]
}
}
]);


According to the docs, you should declare scope: false so that you inherit the scope from the outer controller-scope. Since I use $broadcast which should propagate the event down the hirachy I would except this to work, but it doesn't. My only thought is, that the controller inside the directive always creates an isolated scope.(?)


Aucun commentaire:

Enregistrer un commentaire