【问题标题】:Setting which events I want my directives to listen to设置我希望我的指令监听哪些事件
【发布时间】:2015-04-27 03:37:05
【问题描述】:

我有一个这样的指令:

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

【问题讨论】:

    标签: angularjs angularjs-directive isolate-scope


    【解决方案1】:

    使用$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 吗?

    【讨论】:

    • 啊,是的,我需要使用 $rootScope,因为我希望将指令解耦并让 $rootScope 成为指令中唯一注入的东西,我需要试试这个 XD跨度>
    • 我没有使用$scope,而是使用this
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2010-12-10
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多