I have some text in a hidden textarea. When a button is clicked I would like to have the text offered for download as a .txt
file. Is this possible using AngularJS or Javascript?
To download AngularJS library, go to angularjs.org -> click download button, which will open the following popup. Select the required version from the popup and click on download button in the popup.
Creating the download linkCreate an object URL for the blob object. Create an anchor element ( <a></a> ) Set the href attribute of the anchor element to the created object URL. Set the download attribute to the filename of the file to be downloaded.
You can do something like this using Blob
.
<a download="content.txt" ng-href="{{ url }}">download</a>
in your controller:
var content = 'file content for example'; var blob = new Blob([ content ], { type : 'text/plain' }); $scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
in order to enable the URL:
app = angular.module(...); app.config(['$compileProvider', function ($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/); }]);
Please note that
Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release these automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.
Source: MDN
Just click the button to download using following code.
in html
<a class="btn" ng-click="saveJSON()" ng-href="{{ url }}">Export to JSON</a>
In controller
$scope.saveJSON = function () { $scope.toJSON = ''; $scope.toJSON = angular.toJson($scope.data); var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" }); var downloadLink = angular.element('<a></a>'); downloadLink.attr('href',window.URL.createObjectURL(blob)); downloadLink.attr('download', 'fileName.json'); downloadLink[0].click(); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With