morpheus05
morpheus05

Reputation: 4872

angular Send event to directive

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

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.(?)

Upvotes: 1

Views: 1479

Answers (1)

Gent
Gent

Reputation: 2685

Your example shows a mismatch in naming, the directives name should be alertBox instead of alert-box to have the tag be

Upvotes: 1

Related Questions