如何将值从 Angular 指令返回到控制器中的$scope变量

How do I return a value from an Angular directive to a $scope variable in the controller?

本文关键字:控制器 变量 scope 返回 指令 Angular      更新时间:2023-09-26

我正在使用角度-ua-pivot-table.js我想将更新的表信息保存在控制器的$scope变量中。

以下是整个指令:

  angular.module('ua.pivottable', [])
.directive('pivotTable', pivotTableDirective);
function pivotTableDirective() {
return {
  restrict: 'E',
  link: function (scope, element, attrs) {
    var derivers = $.pivotUtilities.derivers;
    function updatePivotTable(newValue, oldValue) {
      if (newValue) {
        var derived = scope.$eval(attrs.derivedAttributes);
        console.log(derived);
        var finalDerived = {};
        derived.forEach(function (e, i) {
          if (e.type === "date") {
            finalDerived[e.name] = derivers.dateFormat("donationDate", "%m/%d/%y");
            finalDerived[e.name + " (month)"] = derivers.dateFormat("donationDate", "%n");
            finalDerived[e.name + " (year)"] = derivers.dateFormat("donationDate", "%y");
          } else if (e.type === "lookup") {
            finalDerived[e.name] = function (row) { return row[e.attr] || "(none)" }
          } else if (e.type === "hidden") {
            finalDerived[e.name] = function (row) { return "(none)" };
          }
        });
        console.log(finalDerived);
        var pivotData = scope.$eval(attrs.pivotData);
        if (pivotData) {
          var pivotAttrs = $.extend({}, {
            rows: attrs.rows ? scope.$eval(attrs.rows) : undefined,
            cols: attrs.cols ? scope.$eval(attrs.cols) : undefined,
            aggregatorName: attrs.aggregatorName ? scope.$eval(attrs.aggregatorName) : undefined,
            vals: attrs.vals ? scope.$eval(attrs.vals) : undefined,
            rendererName: attrs.rendererName ? scope.$eval(attrs.rendererName) : undefined,
            aggregators: attrs.aggregators ? scope.$eval(attrs.aggregators) : undefined,
            derivedAttributes: finalDerived ? finalDerived : undefined,
            hiddenAttributes: attrs.hiddenAttributes ? scope.$eval(attrs.hiddenAttributes) : undefined,
            onRefresh: function (config) {
              var config_copy = JSON.parse(JSON.stringify(config));
              //delete some values which are functions
              delete config_copy["aggregators"];
              delete config_copy["renderers"];
              //delete some bulky default values
              delete config_copy["rendererOptions"];
              delete config_copy["localeStrings"];
              //$("#output").text(JSON.stringify(config_copy, undefined, 2));
              scope.saveState = config_copy;
              scope.$parent.saveState = config_copy;
              console.log(scope);
            }
          });
          console.log(pivotAttrs);
          angular.element(element)
            .pivotUI(pivotData, pivotAttrs);
        }
      }
    };
    scope.$watchGroup([
      attrs.pivotData,
      attrs.rows,
      attrs.cols,
      attrs.aggregatorName,
      attrs.vals,
      attrs.rendererName,
      attrs.aggregators,
      attrs.derivedAttributes,
      attrs.hiddenAttributes
    ], updatePivotTable, true);
  }
};
}

onRefresh 方法是我一直在工作的地方。每次编辑数据透视表时,表的值都会保存在名为 config_copy 的变量中。我想让我的控制器访问名为 $scope.saveState 的$scope变量中的config_copy。

这是 HTML:

<pivot-table id="pivotTable" class="table" save-state="pivotTable" pivot-data="pivotTable.data"
                       rows="pivotTable.rows"
                       cols="pivotTable.cols"
                       vals="pivotTable.vals"
                       aggregators="pivotTable.aggregators"
                       aggregator-name="pivotTable.aggregatorName"
                       renderer-name="pivotTable.rendererName"
                       derived-attributes="pivotTable.derivedAttributes"
                       hidden-attributes="pivotTable.hiddenAttributes">
          </pivot-table>

以及初始化数据透视表的控制器代码:

var prepPivot = function (savedTable) {
      if ($scope.donations.length>0) {
        console.log('pivotInit', pivotInit)
        var derivers = $.pivotUtilities.derivers;
        var tpl = $.pivotUtilities.aggregatorTemplates;
        var numberFormat = $.pivotUtilities.numberFormat;
        var currencyFormat = numberFormat({ prefix: "$" });
        console.log($scope.donations);
        $scope.derived = [
          {
            name: "Donation date",
            type: "date",
            attr: "donationDate",
          },
          {
            name: "Donation status",
            type: "lookup",
            attr: "status",
          },
          {
            name: "Disbursement status",
            type: "lookup",
            attr: "disbursementStatus",
          },
          {
            name: "$$hashKey",
            type: "hidden",
          }
        ];
        var settings = {
          hiddenAttributes: [],
          derivedAttributes: $scope.derived,
          aggregators: {
            "Donation Count": function () { return tpl.count()() },
            "Receipt Amount": function () {
              return tpl.sum(currencyFormat)(["receiptAmount"]);
            },
          }
        };
        // hide everything, so we can format the columns better
        settings.hiddenAttributes.push('$$hashKey');
        for (var property in $scope.donations[0]) {
          if ($scope.donations[0].hasOwnProperty(property)) {
            settings.hiddenAttributes.push(property);
          }
        }
        if (savedTable) {
          $scope.pivotTable = savedTable;
        } else {
          $scope.pivotTable = {
            rows: ['donationDate'],
            cols: ['disbursementStatus'],
            aggregatorName: 'Donation Count',
            vals: ['receiptAmount'],
            rendererName: 'Table',
            aggregators: settings.aggregators,
            derivedAttributes: settings.derivedAttributes,
            hiddenAttributes: settings.hiddenAttributes,
          };
        }

        console.log($scope.pivotTable);
        $scope.pivotTable.data = $scope.donations;
        pivotInit= true;
      }
    };

如何将config_copy从指令函数 onRefresh() 转换为可以在控制器中访问的 $scope.saveState?

您可以像这样为指令设置 scope 部分:

scope: {
   saveState: "="
}

然后,每次您更改指令中的某些内容时,$scope.pivotTable都会更新。

首先,您的指令是否与您的controller在同一个scope内?如果是这样,那么他们将共享scope,您只需将数据设置为 scope.myData,您的controller将有权访问该变量。如果指令嵌套或隔离在controller中,您还可以使用 scope.$parent 访问控制器。

以下是我最终为将来可能遇到类似问题的人解决这个问题的方式。

我在控制器中创建了这个函数:

  $scope.savePivotTable = function (data) {
    console.log('SAVED!');
    $scope.savedPivotTable = data;
  }

将其添加到 HTML 模板中的指令中:

<pivot-table id="pivotTable" class="table" pivot-data="pivotTable.data"
    rows="pivotTable.rows"
    cols="pivotTable.cols"
    vals="pivotTable.vals"
    aggregators="pivotTable.aggregators"
    aggregator-name="pivotTable.aggregatorName"
    renderer-name="pivotTable.rendererName"
    derived-attributes="pivotTable.derivedAttributes"
    hidden-attributes="pivotTable.hiddenAttributes"
    save-pivot-table="savePivotTable">
</pivot-table>

将其添加到我的指令代码中的范围对象中:

function pivotTableDirective() {
return {
  restrict: 'E',
  scope: {
    pivotData: "=",
    rows: "=",
    cols: "=",
    aggregatorName: "=",
    vals: "=",
    rendererName: "=",
    aggregators: "=",
    derivedAttributes: "=",
    hiddenAttributes: "=",
    savePivotTable: "="
  },
  link: function (scope, element, attrs) {
  // Rest of the directive

然后从 onRefresh 方法内部调用该函数:

var pivotAttrs = $.extend({}, {
 rows: scope.rows ? scope.rows : undefined,
 cols: scope.cols ? scope.cols : undefined,
 aggregatorName: scope.aggregatorName ? scope.aggregatorName : undefined,
 vals: scope.vals ? scope.vals : undefined,
 rendererName: scope.rendererName ? scope.rendererName : undefined,
 aggregators: scope.aggregators ? scope.aggregators : undefined,
 derivedAttributes: finalDerived ? finalDerived : undefined,
 hiddenAttributes: scope.hiddenAttributes ? scope.hiddenAttributes : undefined,
 onRefresh: function (config) {
    var config_copy = JSON.parse(JSON.stringify(config));
    //delete some values which are functions
    delete config_copy["aggregators"];
    delete config_copy["renderers"];
    //delete some bulky default values
    delete config_copy["rendererOptions"];
    delete config_copy["localeStrings"];
    scope.savePivotTable(config_copy);
    $("#output").text(JSON.stringify(config_copy, undefined, 2));
    }
});

这给了我访问权限