Instructions for generating a download button

After receiving assistance on saving JSON as a file on the client side from this source, I managed to create a concise code snippet inside this fiddle.

var link = document.createElement('a');
link.download    = "backup.json";
link.href        = url;
link.textContent = "Download backup.json";

document.getElementById('content').appendChild(link);

I attempted to develop an AngularJS directive that would trigger a method in the scope to retrieve data, but encountered some challenges along the way.

module.directive('myDownload', function ($compile) {
    return {
        restrict:'E',
        scope:{ getData:'&getData'},
        link:function (scope, element, attributes) {
            element.append($compile(
                '<a class="btn" download="backup.json"' +
                    'href=' + scope.getData() + '>' +
                    'Download' +
                    '</a>'
            )(scope));
        }
    };
});

I struggled to transform the functionality of the linked fiddle into a working directive. Can you provide any guidance?

Answer №1

How about trying this out: Fiddle

Below is the directive code for your reference:

module.directive('myDownload', function ($compile) {
  return {
    restrict:'E',
    scope:{ getUrlData:'&getData'},
    link:function (scope, elm, attrs) {
        var url = URL.createObjectURL(scope.getUrlData());
        elm.append($compile(
            '<a class="btn" download="backup.json"' +
                'href="' + url + '">' +
                'Download' +
                '</a>'
        )(scope));
     }
  };
});

Controller details:

module.controller('MyCtrl', function ($scope){
  var data = {a:1, b:2, c:3};
  var json = JSON.stringify(data);

  $scope.getBlob = function(){
    return new Blob([json], {type: "application/json"});
  }
});

Answer №2

I found myself in a similar predicament while trying to resolve an issue. On my Angular page, I had a JSON data retrieved through Ajax which was being displayed as HTML. However, I wanted the original JSON data to be downloadable via a link.

The problem with the approach suggested by the original poster and the highest-voted response is that it involves manipulating the HTML DOM within the controller, contradicting the principles of MVVM. It appears this workaround is necessary because Angular restricts the creation of links for blobs by prefixing 'unsafe:' to the resulting blob URL.

Thankfully, Angular offers a method to whitelist specific URL prefixes to prevent blocking when utilizing URL.createObjectURL()...in this scenario, we include blob

Here is my implementation of this solution running on JSFiddle

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does Object.create accept a function as an argument in JavaScript?

Why is newperson4 successfully created instead of producing an error? See the code below: function person() { } var p = new person(); var q = null; var r = "some string"; var newperson1 = Object.create(p); //Runs without errors. var newperson2 = Objec ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...

Stateprovider view templates in AngularJS

WikiApp.config(function config($stateProvider, $urlRouterProvider) { $stateProvider .state('revision', { url: '/wiki', views: { "main": { controller: 'ListCtrl', ...

The jQuery toggle functionality seems to be malfunctioning

I have created a form that should toggle (hide and show) with the click of a button, but for some reason it's not working. Can someone please take a look at my code below and let me know what I'm doing wrong? $(document).ready(function () { ...

Analyze two sets of JSON data and compile a new JSON containing only the shared values

I am trying to generate two JSON arrays based on a shared property value from comparing two sets of JSON data. this.linkedParticipants =[ { "id": 3, "name": "Participant 2", "email": "<a href="/ ...

Something went wrong with @wdio/runner: unable to establish session

After successfully developing cucumber tests that passed and tested some URLs with Chrome, I encountered errors when uploading to the pipeline despite the tests succeeding. Webdriver generated the following errors: INFO webdriver: DATA { 57[0-0] capabili ...

Prevent the next ajax request from overwriting the parameter value set in the previous request

When my application makes multiple ajax requests, I encounter a problem where the original set of parameters used for each request get changed by subsequent requests, leading to errors. Let's take an example: Request A initially sets an index of 0 in ...

Guide to generating a pop-up on domain-1 with information sourced from domain-2 using jquery, iframes, or any other available method

To clearly explain my issue, I will break it down into steps. In domain-1, I need to insert an iframe or JavaScript code. When domain-1 loads, I want a popup window to appear in the center of the screen, covering the entire page with a faded background. ...

Decoding a JSON object in node.js

{"__v":0,"_id":{"$oid":"55f13d34258687e0bb9e4385"},"admin":true,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3d6ded2c3dfd682f3d4ded2dadf9dd0dcde">[email protected]</a>","last_login":"11:25:24 AM","name ...

Is there an Angular binding alternative to a FallbackValue?

When working in XAML, I often take advantage of the useful FallbackValue binding attribute for instances where immediate data may not be available. This allows me to display placeholder content without setting up design time data. Now I'm exploring A ...

Switch between TrackBall and FlyControls in threejs to change the type of controls being used

My goal is to implement two different control modes in my project: a free "flying" mode and an object-centered (trackball) mode. I want to seamlessly switch between them with the press of a button. Initially, I experimented with TrackBallControls and FlyC ...

Utilizing Regular Expressions to Substitute 'null' in API Data with a Custom String in JavaScript

I'm working with an API to gather information about books, including the title and author. However, I've noticed that some authors' data is returned as 'undefined'. I had the idea of using regular expressions (RegExp) to replace th ...

Prevent the bootstrap dropdown menu from closing when encountering a login error during form validation using ajax and codeigniter

I encountered an issue with my dropdown menu login that utilizes bootstrap ajax and codeigniter. When I attempt to submit the form and there is an error, I have to click multiple times before the error message appears because the dropdown menu keeps closin ...

"What is the proper way to implement the Increment Operator within the Ngoninit() function

When I try to use the increment operator within ngoninit() to change a variable's value, I encounter the following error from the compiler: error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or ...

Building ASP.NET Web Requests and Generating Pages

Although I have only dabbled in ASP.NET for simple tasks recently, I am eager to tackle a more challenging project. My goal is to utilize ASP.NET and Javascript to: Create a web page, such as Default.aspx, that calls a web service The web service (possi ...

Update the knockout values prior to submitting them to the server

Imagine having a ViewModel structured like this with prices ranging from 1 to 100... var Item = { price1: ko.observable(), price2: ko.observable(), price3: ko.observable(), ... ... price100: ko.observable(), name: ko.observable ...

Is it possible to categorize elements for focus and onblur events?

In my search feature, I have implemented an autocomplete div that appears when the user types in a search field. The issue I am facing is that I want the div to disappear when the user clicks outside of it. Here is what I have attempted: //SHOW THE DIV WH ...

The Importance of Node JS Callback Functions

Struggling to grasp the concept of callbacks? Check out this code snippet for authentication using MySQL. function authenticate(username, password, callback) { var query = "SELECT * from mydb.users where username='" + username + "'and BINARY ...

Creating a set of labels using values derived from a collection of objects

Looking for advice on how to loop through a Serialized JSON string using an ajax call in JavaScript. I have 8 labels set up and want to assign each key and value from the JSON string to a different label. Any guidance or feedback is appreciated! I'm ...

The process of deploying production-ready code using webpack and angular2

Currently, my Angular 2 code utilizes both webpack and grunt. During development, I rely on webpack-dev-server as a grunt task. When it comes to preparing the code for production deployment, I handle all minification tasks through Grunt which results in t ...