Is there a way to dynamically update this JSON object with AngularJS?

I have created a web page where users can order reports in PDF format. The implementation was done using Angular. When a user changes the report type, the debug information on the page is updated correctly. However, the request for a report is sent as JSON and I would like the JSON object to be automatically updated as well. Currently, I have to click on the "Create JSON" button for it to be refreshed.

You can view this example on JSFiddle here: http://jsfiddle.net/HenricF/wgvd7wLx/2/

IMPORTANT: The JSON object will not only contain the report type but also various other options such as accounts, languages, and dates. Ideally, the JSON object should update whenever any of these options are changed. My apologies for not mentioning this earlier.

HTML

<body ng-app="OrderPageApp">
<div id="all" ng-controller="ReportController">
    <div id="top">
        <div class="pagesection" id="ChooseReportType">
             <h3>Select report type</h3>

            <select id="dropdownlist" ng-change="setAccountTypes(chosenReport)" ng-options="report.name for report in reports" ng-model="chosenReport"></select>
        </div>
        <div class="pagesection" id="ChooseLanguage">
             <h3>Select language</h3>

            <select id="dropdownlist" ng-options="language.name for language in languages" ng-model="chosenLanguage"></select>
        </div>
        <div class="pagesection" id="IncludeHeadlines">

            <h4>Include headlines</h4>

            <input name="includeHeadlines" type="checkbox" ng-model="includeHeadlines">
        </div>
        <div class="bottom" id="bottom">
             <h4>Selected report</h4>

            <div id="reportName">Name: {{name}}</div>
            <div id="reportCode">Code: {{code}}</div>
            <div id="Language">Language: {{chosenLanguage.code}}</div>
            <div id="includeHeadlines">Include headlines: {{includeHeadlines}}</div>
             <h4>JSON data</h4>

            <input type="button" value="Create JSON" ng-click="showJson()">
            <div id="pdfData"><pre>{{pdfData}}</pre>

            </div>
        </div>
    </div>

JS

    var reportTypes = [{
    name: 'Report type 1',
    code: 1
}, {
    name: 'Report type 2',
    code: 2
}, {
    name: 'Report type 3',
    code: 3
}];

var languages = [{
    name: 'Swedish',
    code: 1053
}, {
    name: 'English',
    code: 1033
}];

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


app.controller('ReportController', function ($scope) {

    $scope.reports = reportTypes;
    $scope.languages = languages;


    $scope.setAccountTypes = function (chosenReport) {
        $scope.name = chosenReport.name;
        $scope.code = chosenReport.code;
    };

    $scope.showJson = function () {
        $scope.pdfData = angular.toJson(new CreatePdfData($scope.name, $scope.chosenLanguage, $scope.includeHeadlines));
    };

    function CreatePdfData(reportType, chosenLanguage, includeHeadlines) {
        this.reportType = reportType;
        this.chosenLanguage = chosenLanguage.code;
        this.includeHeadlines = includeHeadlines;
    };

})

Answer №1

After receiving guidance from deitch and Dipali Vasani, I successfully resolved the issue by updating the pdfData manually whenever there was a change in input.

In order to achieve this in HTML, I utilized the following code snippet:

<input name="includeHeadlines" type="checkbox" ng-model="includeHeadlines" ng-change="showJson()">

Similarly, in JS, I implemented the solution as follows:

$scope.setAccountTypes = function (chosenReport) {
    ...
    $scope.showJson();
};

Answer №2

Check out these modifications:

    var reportTypes = [{
      name: 'Report type 1',
      code: 1
    }, {
      name: 'Report type 2',
      code: 2
    }, {
      name: 'Report type 3',
      code: 3
    }];

    var languages = [{
      name: 'Swedish',
      code: 1053
    }, {
      name: 'English',
      code: 1033
    }];

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


    app.controller('ReportController', function($scope) {

      $scope.reports = reportTypes;
      $scope.languages = languages;

      $scope.setAccountTypes = function(chosenReport) {
        $scope.name = chosenReport.name;
        $scope.code = chosenReport.code;
      };

      $scope.showJson = function() {
        var name = $scope.name;
        var chosenLanguage = $scope.chosenLanguage;
        var includeHeadlines = $scope.includeHeadlines;
        if (name == undefined) {
          name = null;
        }
        if (chosenLanguage == undefined) {
          chosenLanguage = null;
        }
        if (includeHeadlines == undefined) {
          includeHeadlines = false;
        }
        $scope.pdfData = angular.toJson(new CreatePdfData(name, chosenLanguage, includeHeadlines));
      };

      function CreatePdfData(reportType, chosenLanguage, includeHeadlines) {
        this.reportType = reportType;
        this.chosenLanguage = chosenLanguage != null ? chosenLanguage.code : null;
        this.includeHeadlines = includeHeadlines;
      };

    })
<body ng-app="OrderPageApp">
  <div id="all" ng-controller="ReportController">
    <div id="top">
      <div class="pagesection" id="ChooseReportType">
        <h3>Select report type</h3>

        <select id="dropdownlist" ng-change="setAccountTypes(chosenReport);showJson()" ng-options="report.name for report in reports" ng-model="chosenReport"></select>
      </div>
      <div class="pagesection" id="ChooseLanguage">
        <h3>Select language</h3>

        <select id="dropdownlist" ng-options="language.name for language in languages" ng-model="chosenLanguage" ng-change="showJson()"></select>
      </div>
      <div class="pagesection" id="IncludeHeadlines">

        <h4>Include headlines</h4>

        <input name="includeHeadlines" type="checkbox" ng-model="includeHeadlines" ng-change="showJson()">
      </div>
      <div class="bottom" id="bottom">
        <h4>Selected report</h4>

        <div id="reportName">Name: {{name}}</div>
        <div id="reportCode">Code: {{code}}</div>
        <div id="Language">Language: {{chosenLanguage.code}}</div>
        <div id="includeHeadlines">Include headlines: {{includeHeadlines}}</div>
        <h4>JSON data</h4>

        <input type="button" value="Create JSON" ng-click="showJson()">
        <div id="pdfData"><pre>{{pdfData}}</pre>

        </div>
      </div>
    </div>
</body>

JSFiddle

These adjustments should resolve the issue

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

The jstree does not seem to be generating the tree structure as expected based on

I am utilizing the jstree plugin to construct a hierarchical tree view of locations, rooms, and assets for a company within a PHP application that I am developing. The main intention behind this tree is to enable users to select an asset while going throu ...

What could be causing the unusual alignment of the 'pixels' on my resized HTML5 canvas?

Currently, I am in the process of creating a simple HTML5 canvas/JavaScript snake game inspired by the classic Nokia Snake. This is my first attempt at developing a game using HTML5 canvas and JavaScript, and I must admit, I am still a novice programmer! ...

Is optgroup malfunctioning in IE 10?

My main question is: does optgroup not function properly in IE? The Plnkr code works fine in Chrome but encounters issues in IE 10. I'm trying to find a solution that will work across both browsers. Is this a known problem? In Chrome, I can expand/co ...

What is the best method for finding the value of an element?

Here is the snippet of code that I'm working with: if($('span').text().indexOf("t")){ console.log($('span').text()); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <sp ...

Creating customized JavaScript bundles with TypeScript - a beginner's guide

Our ASP.NET MVC application contains a significant amount of JavaScript code. To optimize the amount of unnecessary JS being loaded to the browser, we utilize the BundleConfig.cs file to create multiple bundles. On the View, we implement logic to determin ...

Avoiding file storage of Json data

When scraping a page to gather information for saving in a file, I encountered an issue with writing the data in JSON using the "write-json" library from npm. The problem arises when trying to save all the data, as it stops at a certain point. Here is an e ...

Is there a way to enlarge the font size for a complete tag?

I'm having trouble with a project. One of the tasks is to use jQuery or JavaScript to increase the font size of a paragraph. The console statements are incrementing by +1 with every mouse click (the first click adds 1, the second adds 2, and so on). ...

Save the JSON data into a variable inside a React utility component

Currently, I am new to React and facing an issue with fetching data and storing it in a variable. I have been struggling to understand why my SetMovieResponse function is not working as expected. I have tried stringifying the JSON before sending it, but w ...

Is there a way to adjust the height of one div based on the height of another div in Bootstrap?

I am experimenting with a Bootstrap example featuring a table in the left column and 4 columns in 2 rows in the right column. Check out the code below: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css ...

Embed the Hero slides directly into the gatsby-image-plugin

Looking to transition my "Home hero slide" from hardcoded to dynamic using the gatsby-image-plugin. Visit my site for reference. Current "hardcoded" sections: HeroSlider.js New code here... HeroSlider.styles.js New code here... Slide.js New code ...

The Content Delivery Network is currently experiencing issues operating in parallel

Currently utilizing this CDN: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.js"></script> Additionally, I am also using two other CDNs simultaneously: <script src="https://cdnjs.cloudflare.co ...

How can I align the selected option to the left in a CSS/jQuery selectbox?

I've been struggling to get the selected option aligned left like the other dropdown options. Even though I've added 'text-align:left;' in every CSS option, it's not working. I suspect that the JavaScript code is affecting the al ...

What is the best way to navigate to the bottom of a website, similar to a "back to top

I have implemented a code snippet on my blog to go "Back to top" using a combination of HTML, CSS, and JavaScript. Now I am looking to add functionality for the opposite action, which is to "Go to Bottom". The code for going back to the top looks like this ...

Troubles with AJAX and jQuery

<html> <head> <title>Ajax Example</title> <script type="text/JavaScript" src="jquery-1.5.1.min.js"></script> <script type="text/JavaScript"> function fetchData() { $.ajax({ type: "GET", url: "htt ...

The `encodeAddress()` function in Google Geocode is used to ge

Encountering issues with extracting latitude and longitude values from Google's response. Google is providing XML-like data: "location" : { "lat" : 53.55914120, "lng" : 10.00923520 }, I am trying to parse this using var r = results[0].geome ...

Getting data from an array of JSON arrays in PHP: a comprehensive guide

Here is the response I am receiving from my server script: {"task_id":"1","task_create_time":"2015-08-09 22:48:25","task_end_time":"0000-00-00 ``00:00:00","service_id":"2","task_status":"1","user_id":"1","user_email":"<a href="/cdn-cgi/l/email-prot ...

Issue with JavaScript Onclick Event Handler

Rephrasing Full JavaScript Code. Javascript <div id="PopUp1" style="display: none; color: #FFFFFF;"></div> <div id="Mask"></div> <script type="text/javascript"> var Content = '<p>Content!!!!!</p><input ty ...

Preventing child element clicks in Angular 5: A helpful guide

I have checked numerous references, but unfortunately haven't received any responses. That's why I have turned to this platform in hopes of improving my code with your assistance. I need to add an element with text on click. Currently, it works ...

Utilize Autocomplete component from Material UI to sift through distinct option values

Looking to implement unique options in the dropdown menu of an Autocomplete component from Material UI based on a specific property within a list of objects. The current issue is that duplicate values are appearing in the dropdown, like ['Color1&apos ...

What is the best way to add information to a JObject in C#?

Recently, I created a Json object in C# that represents a development timeline: { "timeline": { "headline": "Development timeline", "type": "default", "text": "timeline", "startDate": "12/12/2011", "date": [ { "star ...