How do I incorporate JSON data in Angular?

When working with the data from a specific service, I found it necessary to utilize the information provided by the following link:

The data contains HTML mixed in, which can be cleaned using an online tool

Below is a snippet of the data obtained:

cb({
        "title": "Recent Uploads tagged london",
        "link": "http://www.flickr.com/photos/tags/london/",
        "description": "",
        "modified": "2015-06-27T17:21:27Z",
        "generator": "http://www.flickr.com/",
        "items": [
       {
            "title": "Citywards",
            "link": "http://www.flickr.com/photos/peterphotographic/19182673346/",
            "media": {"m":"http://farm1.staticflickr.com/269/19182673346_eae48f0d5d_m.jpg"},
            "date_taken": "2015-06-22T20:25:21-08:00",
            "description": " <p><a href=\"http://www.flickr.com/people/peterphotographic/\">peterphotographic<\/a> posted a photo:<\/p> <p><a href=\"http://www.flickr.com/photos/peterphotographic/19182673346/\" title=\"Citywards\"><img src=\"http://farm1.staticflickr.com/269/19182673346_eae48f0d5d_m.jpg\" width=\"173\" height=\"240\" alt=\"Citywards\" /><\/a><\/p> <p>W&amp;DPS City Walk 2015<br /> <br /> Thameside, London, UK<\/p>",
...ETC

To clean and display each item using ng-repeat, what steps should I take?

Access the corresponding Plunker for demonstration purposes at this link

If you are facing difficulty viewing content due to Access-Control-Allow-Origin issues, consider installing this Chrome extension to resolve the problem:

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-ntp-icon

I encountered a similar issue as well.

Answer №1

If you're unable to view anything, it may be due to an Access-Control-Allow-Origin issue. You can address this by installing a Chrome plugin, activating it, and then refreshing the page to see the data and log:

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-ntp-icon

It's not advisable to instruct users to enable Cross Origin Calls as it exposes them to potential security risks. More information can be found at OWASP: CORS, CSRF

The response you're receiving is in JSONP format (JSONP). For cross-domain requests, JSONP should be used.

In your code, change &jsoncallback=cb to &jsoncallback=JSON_CALLBACK because AngularJS requires it for the $http method to work with .success.

Additionally, method: 'POST' is intended for sending data to the server, not retrieving data. To obtain data from the server, use the HTTP GET method.

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $http) {
  $scope.data = null;
  $http.jsonp('http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=JSON_CALLBACK&tags=london')
    .success(function(res) {
      console.log(res.items);
      $scope.data = res.items;
    })
    .error(function() {
      //handle error
    });
});

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f1909f96849d9083df9b82b1c0dfc2df89">[email protected]</a>" src="https://code.angularjs.org/1.3.16/angular.js" data-semver="1.3.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   <hr />
   <div ng-repeat="item in data">
      <div>
        <p>Title: {{item.title}}</p>
        <p>Author: {{item.author}}</p>
        <img ng-src="{{item.media.m}}" />
        <p>Tags: {{item.tags}} </p>
        <p>Published at: {{item.published}}</p>
      </div>
      <hr />
    </div>
  </body>
</html>

Updated Plunker: http://plnkr.co/edit/K8JtNnf2nAioOUrCfuDm?p=preview

Answer №2

It appears that Flickr utilizes JSONP, requiring the callback function name to be provided. In light of this, it seems like the URL being called should resemble the one below:

(please note the updated value of the jsoncallback parameter). Make sure to utilize the JSONP method of HTTP when making the request:

return $http.jsonp('http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=JSON_CALLBACK&tags=london');

Following that, in the controller:

app.controller('MainCtrl', function($scope, $http, getFlickrImages) {
$scope.data = null;
     getFlickrImages.getData().then(function(dataResponse) {
       $scope.data = dataResponse;     
   });

});

$scope.data must contain the retrieved data as a JavaScript object. If it's returned as a string, you can easily convert it into a JavaScript object using the angular.fromJSon() function.

Subsequently, in the user interface, you can implement the following:

<body ng-controller="MainCtrl">
   <div ng-repeat="item in data.items">
      <div>
       <h1>{{item.title}}</h1>
      </div>
    </div>
  </body>

I haven't validated the code, so please consider it provided as-is.

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

Error: The attempt to perform 'toDataURL' on 'HTMLCanvasElement' has failed because tainted canvases cannot be exported

IMPORTANT: Functioning properly on localhost, but encountering issues on a live server (GoDaddy). Problem: A Wordpress plugin is throwing an error when the "preview" button is clicked, which does not occur on localhost. Error: Uncaught DOMException ...

Counting numbers and displaying results using JavaScript with a JSON string

Looking at this JSON string { "ResultSet": { "version": "1.0", "Error": 0, "ErrorMessage": "No error", "Locale": "us_US", "Quality": 40, "Found": 2, "Results": [{ "quality": 72, ...

Is there a way to run a Javascript function only after an onload event has occurred and returned a specific value?

This question may be a bit lengthy, so I'll do my best to provide an explanation. There are two JavaScript functions that need to execute after the page loads - let's call them function1() and function2(). function1() uses AJAX to fetch data fro ...

Types of flow. What sets apart type {} from {||}?

I am unsure of the specific distinctions. I am curious about the variations. ...

The onBlur function is preventing link clicks from being registered

My Navigation Bar includes a React-InstantSearch: <SearchBox /> component that provides Autocomplete functionality. The SearchBox triggers an onChange event to display suggestions, and an onBlur event to hide the box when exiting the search field. Ho ...

When attempting to process JSON using the fetch method, the value for a valid JSON key

Currently, I am facing a challenge wherein I need to fetch data from my REST server to populate the frontend of my UI. This requires me to make requests not only to my own server but also to other servers. One specific request involves retrieving a list of ...

Issue with IonicModal: $scope.ionicModal.show() stops functioning properly following $scope.ionicModal.remove() being called

I have set up an ionic modal. The first time I click on it <label class="list card"> <textarea ng-click="newPost(1); content = '' " placeholder="Write here"></textarea></label> Here is the new post function // Trigger o ...

Obtaining encrypted data in json format

Received some JSON encoded data. How do I access each of the individual elements? Here's an example: $ticket $customer $user {"ticket":{"id":"10909446","number":"152"},"customer":{"id":"3909381","fname":"","lname":"","email":"<a href="/cdn-cgi/l ...

Tips for removing a previous file from an 'input type' in HTML5 FileReader

Here is a file input with an associated function: <img id="uploadPreview"> <div id="changeImage">Change</div> <div id="customImage"> <input type="file" id="myfile" multiple style="display:none" onchange="PreviewImage();" / ...

choosing a specific item using Cheerio that has a period in its class name

I am facing a challenge in extracting information from an HTML document using Cheerio. The HTML content cannot be modified as it originates externally. The specific element I need to extract has a class name containing a dot: <span class='prop-dat ...

Selenium and JavaScript integration for opening new browser tabs

Hello there, I am looking to open new tests ('it' method) in new tabs and currently trying this approach: driver = new Builder().forBrowser('chrome').build(); beforeEach(() => { // driver.manage().window().open('url') ...

Guide on creating an empty ArrayList in JSON using Rest Assured

When serializing the JSON from a POJO class, I encountered an issue where passing null or empty values to the properties in the POJO class resulted in getting [""] in the array list instead of []. Expected: "Key": [] But Received: "Key":[""] This is how ...

Associating Java and Mongo Objects using a customized format

Currently utilizing a Mongo Database and Java with Spring backend. I had initially designed my data structure as follows: "defaultActivation":{ "accounts": ["500026", "500027"] } To map this in Java, I used the following code along with getters and s ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

What is the best way to display a MySQL Nested Set?

I'm currently implementing the nested set model, as illustrated here: My data is hierarchical in nature, essentially a collection of various graphs with nodes and edges, and I am seeking a way to visualize it. While I grasp the concept of the nested ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

Utilize the power of Await Async while iterating through a massive JSON dataset

The data in the JSON file is quite extensive, weighing around 20MB. My goal is to ensure that the age returned is accurate, whether by waiting for the result or looping through the entire file. Currently, the output is always 0 even when the actual age is ...

Skipping code in JavaScript/jQuery function on window load

I have created a function that applies specific CSS rules to elements when the window is fully loaded. Check out my code below: function applyHover() { $('.view_preloader .overlay').css('opacity',1); $('.view_pre ...

Connect to content on the current page

I am facing an issue where the linked heading of a section on the same page is getting lost under the fixed navigation bar when scrolling down. This problem seems to only occur on desktop view as it works fine on mobile preview. Here is the code I am curre ...