2017-07-21 74 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

相關問題