angular 将事件发送到指令

angular Send event to directive

我想从我的视图控制器向指令发送一个事件(我想编写一个通用警报框,它可以通过外部视图控制器的事件接收警报)。我做了以下事情:

在我的视图模板中,我添加了指令:

html 视图模板:

<alert-box></alert-box>

在视图控制器中:

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

我的指令:

.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);
          };
        }]
    }
  }
]);

根据文档,您应该声明 scope: false 以便从外部控制器范围继承范围。由于我使用 $broadcast 应该将事件传播到 hirachy,所以我希望它可以工作,但它没有。我唯一的想法是,指令中的控制器总是创建一个独立的范围。(?)

您的示例显示命名不匹配,指令名称应为 alertBox 而不是 alert-box 以使标记为