簡體   English   中英

向指令發送角度事件

[英]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,它應該將事件向下傳播,所以除了工作之外,我不會這樣做。 我唯一的想法是,指令內的控制器始終會創建一個隔離的作用域。(?)

您的示例顯示命名不匹配,指令名稱應為alertBox而不是alert-box,以使標記為

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM