Utilizing Angular Schema Form to Populate Form Fields with JSON Data

As a hardware engineer venturing into the realm of creating an in-house software tool, I initially thought it would be a straightforward process. However, I've encountered a plethora of unknowns hindering my progress.

My goal is to develop an internal software solution for order management, complete with a valid JSON Schema. Specifically, I aim to establish a webpage where users can input order information via a web form, which will then be stored as a JSON text file. Additionally, I want the ability to load an existing JSON file, pre-fill the form with current data, make modifications, and save the changes.

While I have experience using php and mysql for similar tasks, I opt for utilizing JSON files this time around to facilitate software adjustments without dealing with database structure intricacies. Moreover, I view this project as a valuable learning opportunity.

Currently, I am exploring auto-generated forms through schemaform.io and have successfully implemented the following code:

<!DOCTYPE html>
<html >

  <head>    

  </head>

  <body ng-app="test" ng-controller="FormController">

    <form name="ngform"
          sf-schema="schema"
          sf-form="form"
          sf-model="model"></form>

<script type="text/javascript" src="../bower_components/angular/angular.js"></script>
<script type="text/javascript" src="../bower_components/angular-sanitize/angular-sanitize.min.js"></script>
<script type="text/javascript" src="../bower_components/tv4/tv4.js"></script>
<script type="text/javascript" src="../bower_components/objectpath/lib/ObjectPath.js"></script>
<script type="text/javascript" src="../bower_components/angular-schema-form/dist/schema-form.min.js"></script>
<script type="text/javascript" src="../bower_components/angular-schema-form/dist/bootstrap-decorator.min.js"></script>  

<script type="text/javascript" src="../bower_components/jquery/dist/jquery.js"></script>  


</script>
 
<script>

/*
$.getJSON("data/order.json", function(orderTemplateJson) {
    console.log(orderTemplateJson); // this will show the info it in firebug console
$scope.$broadcast('schemaFormRedraw')
});
*/

var app = angular.module('test',['schemaForm']);
app.controller('FormController', function($scope,$http){
   $scope.schema = {
   // A long long string of text goes here
};

  $scope.form = [
    "*",
    {
      type: "submit",
      title: "Save"
    }
  ];

  $scope.model = {};
})
    </script>

  </body>

</html>

Next on my agenda is loading the JSON schema from a separate file. Attempting to do so within the callback of a getJSON call resulted in the error:

Uncaught Error: [$injector:modulerr] Failed to instantiate module test due to: Error: [$injector:nomod] Module 'test' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

$.getJSON("data/order.json", function(orderTemplateJson) {
    console.log(orderTemplateJson); 
  
    //Moved all the angular module code to here
});

Making various attempts to resolve this issue has proved challenging, mainly due to a lack of expertise in this area. Any guidance provided would be immensely appreciated.

Furthermore, I seek tips on how to pre-load form data from a JSON file that adheres to the schema requirements. Your assistance is highly valued.

Thank you,

/ Martin

Answer №1

When working with Angular, it's important to follow the Angular conventions. One of the first things to remember is to utilize Angular's $http service for loading files instead of using jQuery's $.getJSON. In your controller, you can implement this as follows:

app.controller('FormController', function($scope,$http){
   $http.get("data/order.json").then(
      function success(response) {
        // It's essential to note that since this is an asynchronous operation, 
        // the $scope.schema will be populated after receiving the response
        $scope.schema = angular.fromJson(response.data);
      },
      function error(response) { /* handle error */ });
   // Other tasks can be performed here
});

If needed, refer to the $http API reference for further guidance.

There are various other considerations when utilizing Angular; however, it's beneficial to spend time understanding the Angular way in order to see quick results.

Furthermore, a more efficient approach would be to use $resource instead of $http, as it is specifically designed for interacting with JSON (and RESTful services).

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

Unexpected button behavior sparked by Vue.js

Check out this fiddle I created: https://jsfiddle.net/frvuw35k/ <div id="app"> <h2>Vue Event Test</h2> <form @submit.prevent> <div class="form-group row"> <div class="col-sm-12 i ...

Every div must have at least one checkbox checked

Coding in HTML <div class="response"> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> </div> <div class="response"> <input type="check ...

Redux Dilemma: Stagnant Data in Redux Repository

Struggling to pass data fetched through axios into the Redux store for use in another component. While other actions and reducers are functioning correctly, this one seems to be causing issues. Here is the flow of data: Begin in the Filter component comp ...

Activate Bootstrap modal using an anchor tag that links to a valid external URL as a fallback option

To ensure accessibility for users who may have javascript disabled, we follow a company standard of developing our web pages accordingly. Our target demographic still includes those familiar with VCRs blinking 12:00. One particular challenge involves a te ...

Trouble mapping an array of objects in ReactJS

I'm encountering an issue where I am unable to map through an array of objects in my component. Although I have used this map method before, it doesn't seem to be working now. Can anyone help me figure out what's going wrong? import React, ...

Changing a PHP string into a JSON object

Is there a way to convert a string stored in a database, which is actually a JSON object, into an object/array format instead of keeping it as a string? [{"id_piesa":"8","cantitate_piesa":"12","garantie_piesa":false},{"id_piesa":"30","cantitate_piesa":1 ...

Troubleshooting React-Redux: Button click not triggering action dispatch

I am facing an issue where my action is not being dispatched on button click. I have checked all the relevant files including action, reducer, root reducer, configStore, Index, and Component to find the problem. If anyone can help me troubleshoot why my a ...

Loop through and collapse an Array containing different types of structures within a Dataset using Apache Spark in Java

My Dataset has the following Schema: root |-- collectorId: string (nullable = true) |-- generatedAt: long (nullable = true) |-- managedNeId: string (nullable = true) |-- neAlert: struct (nullable = true) | |-- advisory: array (nullable = true) | ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

What is the best way to make an AJAX request to retrieve data from a database in JSP using Extjs?

Currently, I am utilizing the Extjs framework and have created a servlet to retrieve data from a database. Once the data is retrieved, it is stored in a list and then converted into a JSON array. I am now looking to incorporate this data into a JSP page us ...

Transferring Information from Angular Interface to NodeJS through a JSON Document

I am currently working on establishing a connection between an AngularJS front end and a NodeJS back end application. The main objective is to manipulate data in a JSON file instead of a traditional database. I have attempted to set up the post method on ...

Switch between Light and Dark Modes effortlessly with just one button

I've created a code that effortlessly switches between light mode and dark mode with the press of buttons. However, I'm looking to combine these two functionalities into a single toggle button for ease of use. If anyone can provide insight on how ...

What steps can be taken to address a TypeScript error when a function's parameters may be of two different types?

I'm facing an issue with a simple function that retrieves the address as a string interface AddressType1 { city: string | null; state: string | null; postalCode: string | null; } interface AddressType2 { city: string | null; region: strin ...

Tips for setting up OpenLayers demonstrations on a personal server?

Currently, I'm working with an older version of OpenLayers (4.6.2) and find the provided examples extremely helpful for testing and reference purposes. However, the official web page with updated examples only includes the latest version. I am wonder ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

PHP: Communicating Data with JavaScript

What if my PHP script requires some time to complete its operations? How can I keep the client updated on the progress of the operation, such as during a file download where the estimated time and data size need to be communicated? In PHP, calculating all ...

Discontinuing the mobx autorun feature upon componentWillUnmount

In my componentDidMount, I have the following autorun function: componentDidMount() { this.autoUpdate = autorun(() => { this.setState({ rows: generateRows(this.props.data) }) }) } Unfortunate ...

Concentrate on a specific component within an overlay using jQuery

How can I focus on a specific area within an overlay when adding an item to the cart? I want to make the rest of the overlay darker and the targeted area more visible. See a quick mockup here: https://i.sstatic.net/UpJuc.png Here's the HTML code: & ...

I have the ability to showcase information from a JSON file using AngularJS, although it may not be in the exact manner that

I am currently working with AngularJS 1.6.4 and NeDB. When attempting to retrieve all users from the database using NeDB, it returns a JSON file containing information for every user. I then tried to display this data using AngularJS, but when using ng-re ...

Organize various base arrangements within Angular version 2

One thing I can accomplish in my angularjs application using ui.router is: $stateProvider .state('app', { url: '', abstract: true, template: '<div data-ui-view></div>' ...