2017-07-21 71 views
0

我试图通过两个指令的帮助来获得div标头高度设置内容包装div。但我无法播出这个高度?如何将元素高度从一个指令传递给另一个指令?

无论如何要实现这一目标吗?

CommonDirectiveService.directive('headerHeight', function() { 
    return {  
     restrict: 'A', 
     link: function (scope, element) {   
      scope.$broadcast('send', element[0].offsetHeight); 
     } 
    }; 
}); 

CommonDirectiveService.directive('setContentTop', function() { 
    return { 
     restrict: 'A', 
     require: 'headerHeight', 
     link: function (scope, element, attrs) { 
      scope.$on('send', function (e, data) { 
       console.log(data); 
       element.css('margin-top', data + 'px'); 
      }); 

     } 
    }; 
}); 

HTML

<div id="topPanel" header-height> 
<div class="masterWrapper content-wrapper" set-content-top> 
    @RenderBody() 
</div> 

回答

0

可以使用$rootScope播放非嵌套事件:

$rootScope.$broadcast('send', element[0].offsetHeight); 

$rootScope.$on('send', ..); 

但我会添加类似的回调:

CommonDirectiveService.directive('headerHeight', function() { 
    return {  
     restrict: 'A', 
     scope: { 
      listener: "&" 
     }, 
     link: function (scope, element) {   
      scope.$watch(function() { 
       return element[0].offsetHeight; 
      }, function(val, oldVal) { 
       if (val !== oldVal) { 
        scope.listener({ $height: val}); 
       } 
      }); 
     } 
    }; 
}); 

CommonDirectiveService.directive('setContentTop', function() { 
    return { 
     restrict: 'A', 
     require: 'headerHeight', 
     scope: { 
      margin: "=" 
     }, 
     link: function (scope, element, attrs) { 
      scope.$watch("margin", function(val) { 
       console.log(val); 
       element.css('margin-top', val + 'px'); 
      }); 
     } 
    }; 
}); 

用法:

<div id="topPanel" header-height listener="height = $height"> 

<div class="masterWrapper content-wrapper" set-content-top margin="height"> 
    @RenderBody() 
</div> 

或者不使用第二个指令在所有:

<div id="topPanel" header-height listener="height = $height"> 

<div class="masterWrapper content-wrapper" ng-style="{ 'margin-top': height }"> 
    @RenderBody() 
</div> 
+0

谢谢,但高度不在内容包装中更新。由于两者都是不同的div,怎么会影响高度。 。 – klmuralimohan

+0

看到这个工作jsfiddle:https://jsfiddle.net/y5snqpyy/ – devqon

相关问题