2016-07-06 1 views
0

Я работаю с angular-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. Я хочу предоставить моему контроллеру доступ к config_copy в переменной $ scope с именем $ scope.saveState.

Вот 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() в $ области. saveState, доступ к которому можно получить в моем контроллере?

ответ

1

Вы можете установить раздел Области для директивы, как это:

scope: { 
    saveState: "=" 
} 

И тогда $scope.pivotTable будет обновлять каждый раз, когда вы что-то изменить из директивы.

1

Во-первых, ваша директива внутри того же scope как ваш controller? Если да, то они будут делиться scope, и вы можете просто установить данные на scope.myData, и ваш controller будет иметь доступ к этой переменной. Вы также можете получить доступ к контроллеру, используя scope.$parent, если директива вложен или изолирована в вашем controller.

0

Вот как я решил это решить для всех, у кого могут возникнуть проблемы с чем-то подобным в будущем.

Я создал эту функцию в моем контроллере:

$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)); 
    } 
}); 

Это дало мне доступ

 Смежные вопросы

  • Нет связанных вопросов^_^