AngularJS – button – 依赖前的调用函数或指令

我正在使用ngJsonExportExcel依赖项将JSON导出到EXCEL。

我有一个其他的PHP文件,根据推button从sql中获取数据,以及我想要导出的数据。

导出是由于button的属性而发生的。 我想要发生的是,当我按下button时,它首先加载数据,然后导出。

这是AngularJS:

 $scope.Export_to_csv = function (odid,hour) { $http.get("fetch-sms-list.php?odid="+odid+"&hour="+hour) .success(function (data) { $scope.smslist=data.result; }); } 

这是button(在表中):

 <tr ng-repeat="row in records | orderBy: sortType : sortReverse"> <td>{{ $index +1 }}</td> <td>{{row.pname + " " + row.sname}}</td> <td>{{row.areaname}}</td> <td>{{row.oddate}}</td> <td>{{row.odtime}}</td> <td><button ng-click="Export_to_csv(row.ODid,row.odtime)" ng-json-export-excel data="smslist" report-fields="{'fname': 'Heder 1', 'sname': 'Header 2'}" filename =" 'export-excel' " separator="," class='btn btn-info'> <i class="fa fa-file-excel-o" aria-hidden="true"></i></button></td> </tr> 

但是,正如我所认为的 – 出口首先执行。

有没有办法解决它? 我宁愿避免多个button,即使他们隐藏。

如果你打开插件的源代码:

https://github.com/dtagdev1/json-export-excel/blob/master/src/json-export-excel.js

你会看到它只作为指令/属性。 没有服务,没有什么可以从外面打电话。 所以你有几个方法:

1)改变你的代码,以便dynamic地添加指令并在parsing完http请求之后编译它,将它从HTML中移除:

 // note the add of $event $scope.Export_to_csv = function ($event, odid,hour) { alert("fetch-sms-list.php?odid="+odid+"&hour="+hour); $http.get("fetch-sms-list.php?odid="+odid+"&hour="+hour) .success(function (data) { $scope.smslist=data.result; $event.currentTarget.attr('ng-json-export-excel', ''); $compile($event.currentTarget.contents())($scope); // inject $compile // inject $timeout to be sure it's called after the compile $timeout(function () { $event.currentTarget.triggerHandler('click'); }); }); } 

2)创build你自己的指令,包装这个指令,为HTTP请求的细节添加一个属性,并在它内部执行HTTP请求,然后触发导出

3) 我build议的一个:创build一个服务,为了做到这一点。 如果您打开指令的源代码,则可以获得所需的所有内容。 您也可以为该插件创build一个PR,以便在不使用HTML的情况下使用相同的服务来改进该插件。 您将允许未来的用户轻松解决相同的问题。

尝试使用一个自定义指令,dynamic添加ng-json-export-excel并触发点击 – >就像在这个完整的可运行DEMO FIDDLE中 。 这样你就不需要“隐藏的元素”。

视图

 <div ng-controller="MyCtrl"> <button ng-click="loadData()" data="data" filename="'export-excel'" report-fields="{ body: 'Body' }" loaded="loaded" my-directive> Load data async </button> </div> 

AngularJS应用程序

 var myApp = angular.module('myApp', ["ngJsonExportExcel"]); myApp.controller('MyCtrl', function($scope, $timeout, $http) { $scope.loaded = false; $scope.data = []; $scope.loadData = function() { if (!$scope.loaded) { $http.get('https://jsonplaceholder.typicode.com/posts').then(function (response) { $scope.data = response.data; $scope.loaded = true; }); } } }); myApp.directive('myDirective', function($compile, $timeout) { return { restrit: 'A', replace: false, scope: { loaded: "=", data: "=" }, link: function(scope, element, attrs) { scope.$watch("loaded", function(newValue, oldValue) { if (newValue && newValue !== oldValue) { element.attr('ng-json-export-excel', ''); element.removeAttr('my-directive'); $compile(element)(scope); $timeout(function() { element.triggerHandler('click'); }); } }); } } });