0

我目前在Angular中使用自定義指令來通過監視父div的大小來調整我的angular-nvd3圖表的大小。這種方法很有效,但即使是調整大小的單個圖表,我也必須重新繪製每個圖表。繼承AngularJs指令鏈接功能

是否可以重寫派生自定義指令中的updateHeight和updateWidth函數來刷新每個單獨的圖表,因此我不必通過創建單獨的指令來複制代碼。

angular.module('app.graphs').directive('flexibleDiv', function() { 
    return { 
     scope: { 
      opts: '=' 
     }, 
     link: function (scope, element, attr) { 

      // Watching height of parent div 
      scope.$watch(function() { 
       return element.parent(0).height(); 
      }, updateHeight); 

      // Watching width of parent div 
      scope.$watch(function() { 
       return element.parent(0).width(); 
      }, updateWidth); 

      function updateHeight() { 
       scope.$parent.scatter_api.refresh(); 
       scope.$parent.focus_api.refresh(); 
       scope.$parent.scatter_twoaxis_api.refresh(); 
      } 

      function updateWidth() { 
       scope.$parent.scatter_api.refresh(); 
       scope.$parent.focus_api.refresh(); 
       scope.$parent.scatter_twoaxis_api.refresh(); 
      } 
     } 
    } 

<div class="widget-body no-padding" flexible-div> 
     <nvd3-scatter-chart data="scatter_data" api="scatter_api"></nvd3-scatter-chart> 
     </div> 
    </div> 

回答

1

該指令可以使用表達式結合以限定父表達來調用一個事件:

angular.module('app.graphs').directive('flexibleDiv', function() { 
    return { 
     scope: { 
      opts: '=', 
      onUpdateSize: '&' 
     }, 
     link: function (scope, element, attr) { 

      // Watching height of parent div 
      scope.$watch(function() { 
       return element.parent(0).height(); 
      }, updateSize); 

      // Watching width of parent div 
      scope.$watch(function() { 
       return element.parent(0).width(); 
      }, updateSize); 

      function updateSize() { 
       scope.onUpdateSize(); 
      } 

     } 
    } 

HTML

<div flexible-div on-update-size="scatter_api.refresh()"> 
    <nvd3-scatter-chart data="scatter_data" api="scatter_api"> 
    </nvd3-scatter-chart> 
</div> 

從文檔:

'隔離'範圍對象哈希定義了一組本地sc操作指令元素上的屬性派生的屬性。這些本地屬性對模板的別名值很有用。對象哈希中的鍵映射到隔離範圍上的屬性名稱;該值定義了屬性如何被與母體範圍,經由匹配該指令的元素的屬性:

  • &&attr - 提供了一種在父範圍的上下文中執行的表達式。如果未指定attr名稱,則假定屬性名稱與本地名稱相同。

- AngularJS Comprehensive Directive API Reference -- Scope

+0

感謝@george我會嘗試這個現在 – ganeshran

+0

它的工作原理就像一個魅力。謝謝!! – ganeshran