AngularJs 指令中的继承 link 函数

Inheritance in AngularJs Directives link function

我目前正在 Angular 中使用自定义指令,通过观察父 div 上的调整大小来调整我的 angular-nvd3 图表的大小。这可行,但我必须重新绘制每个图表,即使是正在调整大小的单个图表也是如此。

是否可以覆盖派生自定义指令中的 updateHeight 和 updateWidth 函数以刷新每个 dividual 图表,这样我就不必通过创建单独的指令来复制代码。

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>

该指令可以使用表达式绑定来定义要在事件上调用的父表达式:

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>

来自文档:

The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the directive's element. These local properties are useful for aliasing values for templates. The keys in the object hash map to the name of the property on the isolate scope; the values define how the property is bound to the parent scope, via matching attributes on the directive's element:

  • & or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name.

--AngularJS Comprehensive Directive API Reference -- Scope