Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage.

Here is how the process unfolds:

When a user clicks on the Submit button on the user interface, a JSON file is sent to another component which processes it and generates a response in JSON format. This response JSON needs to be displayed on a webpage.

The Submit button appears on a page named page2.html:

<button name="topage1" class="button-submit" ng-click="generateJSON()">Submit</font></button>

The generateJSON() method includes the following code:

$scope.generateJSON = function(){
   generateIdForComponents();
   addRestrictions();
   
   // REST
   data = angular.toJson($scope.schema, true);
   headers= {
     'Content-Type': 'application/json',
     'Cache-Control':'no-cache',
     'Access-Control-Allow-Origin': '*'
   };

$http.post('http://127.0.0.1:5000/re/z3', data, {headers:headers}).
    then(function(response) {
        console.log("Merge post ", response.data);
        $scope.greeting = response.data;
    });
}});

The routing setup looks like this:

app.config(function($routeProvider) {
  $routeProvider
  .when("/topage1", {
      templateUrl : "page1.html",
      controller : "page1Controller"
  })
  .when("/topage2", {
      templateUrl : "page2.html",
      controller : "page2Controller"
  })
  .when("/results", {
      templateUrl : "outputOffers.html",
      controller : "resultsController"
  })
  .otherwise({
      templateUrl : "page1.html",
      controller : "page1Controller"
   });
});

What steps should I take to ensure that the JSON data is correctly displayed on outputOffers.html?

Answer №1

If you want to display the response json data on a separate page after generating it in your $scope.generateJSON method, I recommend redirecting to the outputOffers results page and passing the json data as a parameter.

In the resultsController, you can then assign this passed json data to a variable like $scope.greeting, which can be used in your outputOffers view.

To pass parameters between views, make use of the routeParams service and inject it into your resultsController.

Add the $location service in your page2Controller for redirection purposes by injecting it alongside $scope:

myApp.controller("page2Controller", function($scope, $location){... 

Your generateJSON method within the page2 controller should include actions like generating components ID, adding restrictions, converting data to JSON format, and making an HTTP post request with appropriate headers. Upon successful data retrieval, redirect to the results page while passing the json data as a parameter using $location.

resultsController

Don't forget to inject the $routeParams in your resultsController to capture any parameters sent via the URL:

myApp.controller("resultsController", function($scope, $routeParams){...

In the resultsController, check if the jsonData parameter exists (sent from page2) before assigning it to $scope.greeting. This allows proper handling based on whether the parameter is present or not.

(function() {
  if($routeParams.jsonData == null || $routeParams.jsonData === ""){
    $location.path('topage2'); // Redirect to page2 if jsonData is missing
  } else {
    $scope.greeting = $routeParams.jsonData; // Assign jsonData to scope
    console.log($scope.greeting); // Log the data for verification
  }
})();

Utilize the $scope.greeting variable in your outputOffers.html view to display specific properties from the json object:

<p>{{greeting.title}}</p>
<p>{{greeting.message}}</p>

Update:

Based on the snippet of your json provided, iterate through the json data in the outputOffers.html view using ng-repeat:

<div ng-repeat="g in greeting"> 
  <p>id: {{g.id}}</p>
  <p>clockspeed: {{g.offer.clockSpeed}} </p>
</div>

Answer №2

To enhance the functionality, consider creating a service with two distinct functions - one for storing and another for fetching values. The function responsible for storing the value can be integrated into the 'page2Controller', while the function for fetching the value should be placed in the resultsController.

Check out this brief tutorial to guide you through:

app.config(function($routeProvider) {
  $routeProvider
  .when("/topage1", {
      templateUrl : "page1.html",
      controller : "page1Controller"
  })
  .when("/topage2", {
      templateUrl : "page2.html",
      controller : "page2Controller"
  })
  .when("/results", {
      templateUrl : "outputOffers.html",
      controller : "resultsController"
  })
  .otherwise({
      templateUrl : "page1.html",
      controller : "page1Controller"
   });
});

app.service('greetingService', function() {
    this.greeting = '';
    this.store = function (greeting) {
        this.greeting = greeting;
    }
    this.fetch = function () {
      return this.greeting;
    }
});

For instance, here's how the page2Controller should be structured:

app.controller('page2Controller', function($scope, greetingService) {
  $scope.generateJSON = function(){
   generateIdForComponents();
   addRestrictions();
   // REST
   data = angular.toJson($scope.schema, true);
   headers= {
     'Content-Type': 'application/json',
     'Cache-Control':'no-cache',
     'Access-Control-Allow-Origin': '*'
   };

$http.post('http://127.0.0.1:5000/re/z3', data, {headers:headers}).
    then(function(response) {
        console.log("Merge post ", response.data);
        greetingService.store(response.data);
    });
}});
});

The resultsController implementation would resemble the following:

app.controller('resultsController ', function($scope, greetingService) {
  $scope.greeting = greetingService.fetch();
});

Lastly, remember to include this snippet in your 'outputOffers.html' file:

{{greeting}}

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

Sending arguments from JavaScript to PHP via ajax

I am facing a challenge where I need to send a JavaScript variable to a PHP function. While I was successful in doing this with hard-coded values, I'm struggling when it comes to using variables. Here's an example of what worked for me: <butt ...

What is the method for fetching the unprocessed value of a directive attribute in Angular?

I created a custom directive that uses $observe to monitor any changes in the value of an attribute. When this event occurs, I want to access the uncompiled value of the attribute, not the compiled value. Here is how my HTML code looks: <div my-attrib ...

Node.js express version 4.13.3 is experiencing an issue where the serveStatic method is not properly serving mp3 or

I am currently utilizing Express 4.13.3 along with the serve-static npm module to serve static assets successfully, except for files with mp3 or ogg extensions. Despite reviewing the documentation, I have not come across any information indicating that thi ...

Adjust the size of the external JavaScript code

Is it possible to adjust the size of the div element created by the external javascript code below? I've tried wrapping it in a div and setting the width, but the resizing doesn't seem to work. <div width = "100"><script type="text/jav ...

I am facing an issue where my AngularJS code is not executing properly on JSF

I'm trying to clear the text inside a textarea using AngularJS after typing and clicking on a button. Here's the link to the fiddle for reference: http://jsfiddle.net/aman2690/2Ljrp54q/10/ However, I keep encountering the following error messag ...

Update data in PHP dynamically without reloading the page

It would be great if they are doing well! I have encountered a minor issue - everything seems to work perfectly, but it doesn't quite meet my requirements. I am referring to this particular function: <script> var previous = null; var current = ...

Modifying the content within a DIV element

I want to make changes to my DIV. <div id="main"> <div id="one"> <div class="red"> ... </div> <img class="avatar" src="img/avatar1.jpg"/> <span class="name"> John < ...

Tips for designing a multi-level dropdown navbar

I am currently facing an issue with designing a navbar. I am aiming for Multi-Level Dropdowns, but whenever I click on More Services, it automatically closes the main dropdown menu. I have experimented with various approaches, but none of them seem to be ...

Encountering an unexpected error: receiving a void element tag as input in React

Any ideas on how to resolve the following error message: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` Check out my code snippet below: import "./styles.css"; export default function App() { re ...

"Integration error: specified token_name parameters are invalid." FORTPAY INTEGRATION

I have been following the instructions provided by payfort in their email and referring to the Merchant Page 2.0 documentation for integration with nodejs. Despite sending all the necessary parameters in the request body, I encountered an issue where the T ...

Unable to extract property from object in context due to its undefined status

Having trouble with the useContext hook in my React app for managing the cart state. Keep getting an error stating that the function I'm trying to destructure is undefined. I'm new to using the context API and have tried various solutions like e ...

Reordering sections in a dynamic manner

I'm working on a single-page website with four sections arranged like this: <section id=“4”> <section id=“3”> <section id=“2”> <section id=“1”> Now, I want to change the order of these sections when scrolling ...

Is there a way to turn off alerts from Aspx files for HTML and CSS?

Dealing with annoying warnings in my aspx files has been a constant struggle. The "CSS Value is not defined" message pops up when I reference CSS files from different projects, causing unnecessary frustration. Even more frustrating are the warnings about i ...

JavaScript is proving to be uncooperative in allowing me to modify the

Despite searching through previously asked questions, I have been unable to find a solution to my issue. I am struggling with changing an image source upon clicking the image itself. The following is a snippet of my HTML code: <img id="picture1" oncli ...

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

The Datepicker and Tablesorter dilemma

Having a Datepicker and Tablesorter on the same View Page presents an issue for me. When I remove the tablesorter, the datepicker functions properly. However, when I reintroduce the tablesorter, the datepicker stops working entirely. Below is the code sni ...

Mastering asynchronous function handling in Node.js

I'm currently experiencing an issue with printing two statements using two functions var mongoose = require( 'mongoose' ); var_show_test = mongoose.model( 'test' ); exports.showTest = function(req,res) { var jsonString = []; ...

Tips for incorporating an onClick event into a variable beyond the class extension

Currently utilizing React/Redux in this scenario. At the beginning of my code, outside of the class extends block, I have: const Question10 = () => (<div> <p>Insert question here</p> <input place ...

Strategies for Applying Filters in Search Feature on IOS Devices

Currently, I have an array of books that are being displayed on my view. At the top of the view, there are 3 filters available: (All | Reading level 1 | Reading Level 2 | Reading Level 3) (All | Informational | Literature) (All | Published in 2000-2005 | ...

What is the process for setting a cookie that allows for reading from the same domain with a different port?

After setting my cookie in C# code with Request.Cookie["NTLogin"].Value="XYZ", I encountered an issue when attempting to read this cookie from a new application built in Angular JS. To access the cookie, I used $cookies.get('UserNTLogin'). The p ...