0

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

是否可以在派生的自定义指令中覆盖 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>
4

1 回答 1

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>

从文档:

“隔离”范围对象哈希定义了一组从指令元素的属性派生的本地范围属性。这些本地属性对于模板的别名值很有用。对象哈希中的键映射到隔离范围上的属性名称;这些值通过指令元素上的匹配属性定义属性如何绑定到父范围:

  • &&attr- 提供一种在父作用域的上下文中执行表达式的方法。如果未指定 attr 名称,则假定属性名称与本地名称相同。

-- AngularJS 综合指令 API 参考 -- 范围

于 2016-08-15T18:45:16.340 回答