Generating a JSON download link using AngularJS

I'm attempting to generate a link that will enable the download of a JSON file in this way

Controller

$scope.url = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

View

<a href="url" download="download.json">download</a>

However, upon inspecting the resulting HTML code, I notice that unsafe: is added at the beginning of the href value, causing the link to malfunction.

I have made unsuccessful attempts to use different approaches from the $sce service to indicate to Angular that this URL should be trusted.

Answer №1

For a live demo, check out this fiddle: https://jsfiddle.net/54wftbg2/7/

<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e88080885aabac8d81afa79ae6b8bcb596a9ada5"><span class="_cf_email_">[email protected]</span></a>" data-semver="1.5.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
  <a href="{{jsonUrl}}" download="download.json">download</a>
</div>

<script type="text/javascript">
    var app = angular.module("app", []);

    app.config( [
        '$compileProvider',
        function( $compileProvider )
        {   
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|data|chrome-extension):/);
            // Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
        }
    ]);

    app.controller("MainCtrl", ["$scope", function($scope) {

      var jsobObj = { name: 'Elena', age: 32 };
      var jsonData = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(jsobObj));

      $scope.jsonUrl = 'data:' + jsonData;

    }]);
</script>

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

Internal server error encountered while making an AJAX call using AngularJS routing

I'm currently diving into AngularJS with a basic application focused on customers and their orders. The issue I'm encountering involves a table that showcases the list of customers along with a link to access their respective orders. However, upo ...

Updating the content of a window without the need to refresh the page using JavaScript

Is there a way to navigate back to the previous window in chat_user without refreshing the entire page when the back button is clicked? Below is the code I have tried: <a href="" onclick="window.history.go(-1); return false;">back</a> ...

What's the best way to organize a list while implementing List Rendering in VueJS?

Currently, I am working on List Rendering in Vue2. The list is rendering correctly, but it appears ordered based on the data arrangement in the array. For better organization, I need to sort each item alphabetically by title. However, I am facing difficult ...

Maximizing Input Field Utility in React JS

I have a challenge with retrieving values from the input field and passing it to the useEffect. I specifically want the search to be triggered only after pressing the onSearch function. The issue is that I can only capture the value using the onChange func ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

Utilizing Jquery to add a delay and animate the sliding up effect on a recently created element

I am looking to apply a slide-up effect to a newly created element after a specified delay. $("div[data-error='true']").delay(5000).slideUp(500, function () { $("#error-alert").remove(); }); $("div[data-success='true']").delay(5000 ...

Designing a menu header against a specific background color resulting in misalignment

I have been working on creating a menu header for my website. If you would like to take a look, here is the link to my jsfiddle page. Unfortunately, I am facing an issue where all my images and text should remain in that grey color scheme but somehow it& ...

Tips for eliminating unnecessary module js calls in Angular 9

Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module JS files and ensure that only nece ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

The data in the loaded angularjs 2 select box is not showing up in the browser

I am encountering an issue with a select box that is being populated from a database. Although the select box template is loading in the browser with all the data from the database, it is not visible in the UI within a table. Controller.js: $scope.GetCvS ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

How effective is Dojo CodeGlass?

When working with Dojo, I have encountered a situation where the sample codes should be functional based on the references provided. However, after attempting to run the code, I am faced with a blank page. It seems as though I may have overlooked somethi ...

Error with JavaScript callback functions

After creating a POST route, I encountered unexpected behavior in the code below. The message variable does not display the expected output. app.post("/", function (req, res, error) { var message = ""; tableSvc.createTable("tableName", function (error ...

When choosing from multiple dropdown menus, the selected option should be hidden from the other dropdowns

I'm currently working on a project that involves designing a web form incorporating 3 select boxes with multiple questions. The concept is such that, if I choose the 1st Question from the 1st select drop-down, it should not be available in the 2nd sel ...

Perform a Fetch API request for every element in a Jinja2 loop

I've hit a roadblock with my personal project involving making Fetch API calls to retrieve the audio source for a list of HTML audio tags. When I trigger the fetch call by clicking on a track, it always calls /play_track/1/ and adds the audio player ...

How can I merge these two Observables in Angular to create an array of objects?

Let's say we are working with two different datasets: student$ = from([ {id: 1, name: "Alex"}, {id: 2, name: "Marry"}, ]) address$ = from([ {id: 1, location: "Chicago", sid: 1}, {id: 2, location: &qu ...

The concept of 'this' remains undefined when using a TypeScript Property Decorator

I've been delving into TypeScript decorators focusing on properties, and I crafted the following snippet inspired by various examples: decorator.ts export function logProperty(target: any, key: string) { let val = this[key]; const getter = () ...

What are some methods to conceal an email address using Javascript?

let user = 'alex'; let domain = 'gmail.com'; let send = 'msg'; document.getElementById("email").href = "ma" + send + "ilto:" + user + "@" + domain; <a id="email"> <img src="imgs/pic.jpg"> </a> I have been w ...

Using AngularJs ngBind may cause syntax highlighted code snippets to not display properly

For my web application, I utilized a Syntax highlighting API to highlight code snippets. To achieve this, I integrated highlightjs. Within a popup modal, I included the <pre> tag and expected it to display my highlighted xml string when opened. HTML ...

How can AJAX be used to execute a PHP script that deletes a record from a database table?

Yesterday, I asked for help on how to save user-generated blog posts and I successfully tackled the database aspect of it. Now, my next goal is to be able to delete a blog post upon clicking a button with an onclick event. After researching extensively onl ...