设置我希望指令监听的事件

Setting which events I want my directives to listen to

我有这样的指令:

'use strict';

angular.module('epw')
  .directive('md-title', function ($rootScope) {
    return {
      scope: {
        listenTo: '@'
      },
      controller: function () {
        $rootScope.$on('event', function (e, msg) {
          console.log('do something');
        }); // how to I dynamically change what to listen to using the scope `listenTo`
      },
      controllerAs: 'ctrl',
      bindToController: true,
      templateUrl: 'md-title.html'
    }
  });

我有这个:

<md-title listen-to="TITLE_SELECTION_UPDATED"></md-title>

<div class="m-section-header">
  <h1 class="epw-header">{{ctrl.title}}</h1>
</div>

使用 $scope.listenTo 作为要侦听的事件...

controller: function($scope, $rootScope) {
    $rootScope.$on($scope.listenTo, function (e, msg) {
        console.log('do something');
    }); 
}

注意:我还将 $scope$rootScope 注入到指令的控制器函数中。

注意 #2:我不确定您为什么使用 $rootScope.$on 而不是 $scope.$on 作为事件侦听器。您确定要为此使用 $rootScope 吗?