0

Access directive data from a controller from a separate file. Wanted to access the data from SheetJSImportDirective which is the $scope.$apply function that contains $scope.opts.data. The $scope.opts.data is the data I wanted to access the controller on a separate file. Don't worry about the integrations of the directive and controllers including factories I have already made it possible, just wanted to know the best way to access the data from the directive to a controller on a separate file. I wanted to know the supported way or the best way of making it possible. Thank you.

And in my Controller with a function like for example below.

me.accessDataHere = function() {
  //When this function is called , access  $scope.opts.data = data; from SheetJSImportDirective
}

Directive Function

function SheetJSImportDirective() {
  return {
    scope: { opts: '=' },
    link: function($scope, $elm, reportsDirCtrl) {
      $elm.on('change', function(changeEvent) {
        var reader = new FileReader();

        reader.onload = function(e) {
          var bstr = e.target.result;
          var wb = XLSX.read(bstr, { type: 'binary' });
          var wsname = wb.SheetNames[0];
          var ws = wb.Sheets[wsname];

          var aoa = XLSX.utils.sheet_to_json(ws, { header: 1, raw: false });
          var cols = [];
          for (var i = 0; i < aoa[0].length; ++i) cols[i] = { field: aoa[0][i] };

          var data = [];
          for (var r = 1; r < aoa.length; ++r) {
            data[r - 1] = {};
            for (i = 0; i < aoa[r].length; ++i) {
              if (aoa[r][i] == null) continue;
              data[r - 1][aoa[0][i]] = aoa[r][i]
            }
          }

          /* update scope */
          $scope.$apply(function() {
            $scope.opts.columnDefs = cols;
            $scope.opts.data = data;
            testdata()
            console.log("JSON Data :", $scope.opts.data)

          });
        };

        reader.readAsBinaryString(changeEvent.target.files[0]);
      });
    }
  };
}
Community
  • 1
  • 1
  • If you're using and $ctrl.opts = {} is in your controller, then updating the opts.columnDefs and data within the $apply should be readily available in the controller scope. How are you using the SheetJSImportDirective within the controller/template? – kendavidson Apr 16 '19 at 14:36
  • Having the `` element act as both a file selector and a conversion service violates the principle of [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns). I would re-factor the code to have the `` element only act as a file selector. Then move into a service the code that uses XLSX. The `ng-model` directive is well integrated with the AngularJS framework. Use [ng-model for ``](https://stackoverflow.com/a/43074638/5535245). – georgeawg Apr 16 '19 at 15:16

0 Answers0