Angular:忽略self发出的消息

时间:2015-01-22 23:04:25

标签: javascript angularjs events javascript-events

我有一个扩展和关闭div高度的指令。它使用了多次,所以当用户打开一个盒子时,我想关闭其他打开的盒子。我认为最好发出一个事件,但问题是该指令也会自行关闭,所以没有div可以打开。

我可以忽略来自同一指令的消息吗?

angular.module('cinemaApp')
.directive('expand', function ($rootScope) {
 return {
  restrict: 'A',
  link: function postLink(scope, element, attrs) {
    $rootScope.$on('contract', function(payload) {
      element.css('height', attrs.fixedheight);
    });

    scope.$watch('open', function(value) {
        element.css('height', (value ? 'auto' : attrs.fixedheight));

      $rootScope.$emit('contract');
    });
    element.css('height', attrs.fixedheight);
  }
 };
});

1 个答案:

答案 0 :(得分:2)

发出事件时,可以传递给侦听器的其他参数。所以你可以像

那样发射
$rootScope.$emit('contract', element);

听着

$rootScope.$on('contract', function(event, target) {
  if (target != element)
    element.css('height', attrs.fixedheight);
});
相关问题