Modify data in JSON using ngModel and then send it via HTTP POST request

Greetings, I am relatively new to Angular and find myself in a bit of a quandary. It seems like the solution to my issue might be simpler than I think.

My Angular App consists of a basic "Page View/Controller" and an "Admin View/Controller" that both utilize the same JSON files for data population.

Naturally, I aim to Carry Out Create, Read, Update, and Delete (CRUD) operations on elements within the Admin View, which essentially means modifying my JSON file.

Here's a snippet from my JSON file:


{
  "id": 22,
  "title": "",
  "section": "expositions",
  "text": "2005 : « Ce soir la lune reve » (Casa de Francia et IFAL - Mexico DF)",
  "url": "",
  "fr": "",
  "es": "",
  "en": "",
  "active": false
},
{
  "id": 23,
  "title": "",
  "section": "expositions",
  "text": "2006 : « Ce monde rayonnant » (Espace Triangle - Bruxelles, Belgique)",
   "url": "",
   "fr": "",
   "es": "",
   "en": "",
   "active": false
}

I have all these elements within my controller's scope:

$http.get('http://example.com/js/texts.json').then(function (result){
   $scope.texts = result.data;
});

Everything is functioning as expected, and I can populate my view using ngModel.

<ul class="angular-content">
   <li ng-repeat="expo in texts | filter:{section: 'expositions'}">
    <h4>
      <input type="checkbox" ng-model="expo.active">
      <textarea rows="2" cols="124" ng-model="expo.text"></textarea>
    </h4>
    <h4 ng-show="expo.fr"><a target="_blank" href="{{expo.fr}}">FR</a></h4>
    <h4 ng-show="expo.es"><a target="_blank" href="{{expo.es}}">ESP</a></h4>
    <h4 ng-show="expo.en"><a target="_blank" href="{{expo.en}}">ANG</a></h4>
  </li>
</ul>

The issue arises when I attempt to modify the values of those <textarea>s and update my JSON file accordingly.

$scope.saveTexts = function () {
$scope.newTexts = JSON.stringify($scope.texts);
$http({
  method: 'POST',
  url: 'http://example.com/js/text.json',
  data: $scope.newTexts,
  contentType: 'application/json; charset=utf-8',
  dataType: 'json'
});

}

I suspect it may be a matter of asynchronous calls or the way I'm implementing JSON.stringify. When I log to the console, my changes do not reflect immediately.


Adding a new element also poses challenges:

If I use this function within an ng-click, the view updates and displays the added element, but it doesn't reflect in $scope.texts

$scope.addExpo = function(){
$scope.texts.push({
  "id": 35,
  "title": "TEST",
  "section": "expositions",
  "text": "TEST",
  "url": "TEST  ",
  "fr": "",
  "es": "",
  "en": "",
  "active": true
});

Thank you in advance for your assistance, and apologies for the lengthy post.

Answer №1

It's not possible to directly save data to a JSON file using an $http request. Here are some suggestions:

  • Implement a server-side script (such as PHP, Ruby, Python, etc.) to handle requests from Angular
  • Consider using ngResource for efficient CRUD operations

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

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Updating JSON multiple times in the same row with different JSON paths

Looking to make multiple updates to a JSON data present in a row? Here's an example of the JSON structure: { "secondaries": [ { "secondaryId": 1, "primaries": [ { "primary": 1 ...

Designing personalized plugins with Typescript in Nuxt

In my Nuxt project, I have implemented a custom plugin file that contains an object with settings called /helpers/settings: export const settings = { baseURL: 'https://my-site.com', ... }; This file is then imported and registered in /plugi ...

Can the swap operation be carried out using web3.js and a forked HardHat implementation?

Embarking on my journey into ethereum development, I am currently engrossed in crafting a basic script that facilitates swaps using web3.js. To begin with, my web3 is establishing a connection to the HardHat forked server. The first step involves setting ...

Extracting information from a website using Python and saving the results into a file

I have been working on a project where I need to retrieve data from a webpage (http://www.usgs.gov/) using Python and JSON. The script I found in a tutorial worked perfectly when executed, but I encountered errors when trying to save the output to a loca ...

Using Higher Order Components in React with TypeScript to pass a component as a prop

Exploring the steps outlined in this guide: https://reacttraining.com/react-router/web/example/auth-workflow. Attempting to replicate the code: const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props = ...

Using the .get() method to retrieve Firebase documents results in an error message saying "'is not a function'"

I'm currently attempting to retrieve all the documents from a specific collection in Firebase using the following code snippet: const userCollectionRef = collection(db, currentUser?.uid) const snapshot = await userCollectionRef.get() for (const doc of ...

When I try to load JSON data using the http.get() method in my Angular 2 template, it returns

I've encountered an issue while attempting to read and parse a local json file into a custom class I created. The problem arises when trying to access properties of the class, as it throws errors indicating that the class is either null or undefined. ...

Decoding Lodash: Unveiling the findwhere and copy operator in the realm of

Could someone please explain why using Lodash to fetch an object with findWhere allows for a reference copy that enables dynamic changes based on user actions, while the same operation using the copy operator fails to update the source object? I have creat ...

Trouble handling Ajax response

I have two JSP files described below. The parent JSP page contains a Select dropdown box with two options. Another JSP file, dispTable.jsp, displays select boxes inside a table. If the user selects "one" from the dropdown in the parent.jsp page, I want ...

Guide on extracting nested JSON data values using JavaScript

{ "_id" : ObjectId("587f5455da1da85d2bd01fc5"), "totalTime" : 0, "lastUpdatedBy" : ObjectId("57906bf8f4add282195d0a88"), "createdBy" : ObjectId("57906bf8f4add282195d0a88"), "workSpaceId" : ObjectId("57906c24f4add282195d0a8a"), "loca ...

Making a reference to the parent loop within a nested loop

I have a specific goal in mind. I have two tables in my database - 'regions' and 'distributors', both containing a region_id column. My objective is to achieve the following: 1) Iterate through the 'regions' table, creating a ...

Enhancing HTML with VueJS and managing imports

After successfully developing a Single Page Application using VueJS, I realized that the SEO performance was not up to par. To combat this, I decided to create a standard HTML website with some pages incorporating VueJS code (since my hosting environment d ...

Display an icon within an HTML element when the content inside it exceeds its boundaries

Looking to display a copy to clipboard icon when the content inside a div overflows I am using ngFor to iterate through four divs, and if any of those divs is overflowing, I want to show an icon specific to that respective div. <div *ngFor div of Four ...

retrieve information from collections of variables

Having trouble with the code implementation, I'm using PHP version 5.3.3 and not sure how to fix this issue. Array ( [product] => Array ( [0] => apple [1] => banana [2] => orange ) ...

Error 500 occurred when attempting to access an external PHP file

I am currently utilizing WP Web Scraper version 3.2. When I place the shortcode or template tag (php code) directly into my page, the plugin functions correctly and displays the values. However, when I attempt to include the template tag in an external php ...

Guide on converting a material datepicker date value into the format "MM-DD-YYYY" in Angular 6

I need help formatting the date below to MM-DD-YYYY format in my Angular 6 project. I've checked out various solutions on SO and other websites, but so far, none have worked for me. Currently, I am using Material's Angular DatePicker component. ...

Observe the present time in a specific nation

Is there an authorized method to obtain and showcase the current accurate GMT time instead of relying on the easily manipulable local time on a computer? I am looking for a reliable way to acquire the current time in hours/minutes, so I can make calculati ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...

What could be causing my JavaScript pricing calculator to malfunction?

I've been struggling to make the script below work, but I can't seem to figure out why. It should be functioning properly. Even though all variables are in place, no price is appearing? You can view the HTML on this page: var cake_prices = n ...