监听来自指令内控制器的广播事件

Listen for broadcast event from controller within directive

本文关键字:广播 事件 控制器 指令 监听      更新时间:2023-09-26

我有一个控制器,当一些内容加载时广播一个事件,像这样

angular.module('myApp')
  // Using rootScope now
  .controller('SubCtrl', ['$rootScope', '$scope', '$http', function ($rootScope, $scope, $http) {
    $http.get('/scripts/data/content.json')
      .then(function(response) {
        $scope.content = response.data;
        $rootScope.$broadcast('dataloaded');
      });
}]);

在matchHeight指令中,我正在监听数据加载的事件

angular.module('myApp')
  .directive('matchHeight', ['$timeout', function ($timeout) {
    var linkFunction = function(scope, element, attrs) {
      scope.$on('dataloaded', function() {
        $timeout(function() {
          angular.element(element).matchHeight(attrs);
        });
      });
  };
  return {
    restrict: 'A',
    link: linkFunction
  };
}]);

我使用ui-router来管理状态这是HTML

<div class="row usps">
  <div class="col-sm-4 usp-block" ng-repeat="block in content.marketing" match-height>
    // Inner HTML
  </div>
</div>

广播事件不会从指令中获取。我做错了什么?

因为你在ngRepeat内部,内容只会在广播触发器之后呈现,所以指令会。然后你的指令链接将只订阅事件,但它不会执行,因为它已经执行之前,ngRepeat完成渲染你的指令。

为了解决这个问题,ngRepeat将在每次更改数组时重新创建您的列表,指令将在必要时始终被重建,因此您不必收听事件。

angular.module('myApp')
  .directive('matchHeight', ['$timeout', function ($timeout) {
    var linkFunction = function(scope, element, attrs) {
      $timeout(function() {
        angular.element(element).matchHeight(attrs);
      });
  };
  return {
    restrict: 'A',
    link: linkFunction
  };
}]);