我有一个这样的指令:
'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
吗?