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



我有一个这样的指令:

'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吗?

最新更新