What is the best way to insert a new record into a JSON file using AngularJS?

I encountered an issue while attempting to add records to a JSON file using AngularJS. I suspect there might be an error in my code.

Can someone provide guidance on the correct way to achieve this task?

Here is a link to my sample code on Plunker: Plunker Sample Code

 myApp.controller('ToddlerCtrl', function ($scope,$http) {

  $http.get('taskList.json').success(function (data){
    $scope.tasks = data;
});

   $scope.addEmp = function(){

    $scope.bla="sijs";
    $scope.tasks.push({ task:$scope.empName, priority:$scope.empCity, status:$scope.empState });


  var dataObj = {
            task : $scope.empName,
            priority : $scope.empCity,
            status:$scope.empState
    };  
    var res = $http.post('taskList.json', dataObj);
    res.success(function(data, status, headers, config) {
        $scope.message = data;
    });
    res.error(function(data, status, headers, config) {
        alert( "failure message: " + JSON.stringify({data: data}));
    }); 

}

});

Answer №1

Your controller code is solid, but there's a small issue with your form for adding new tasks. The form needs to be placed within the same div as your controller so that it can inherit the necessary scope. Without this, the bindings for empName, empCity, empState, and addEmp won't function properly since they belong to ToddlerCtrl.

To correct this, make sure your HTML resembles the following structure:

<html ng-app="myApp">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98f9f6ffedf4f9eab6f2ebd8a9b6aab6af">[email protected]</a>" data-semver="1.2.7" src="http://code.angularjs.org/1.2.7/angular.js"></script>
     <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>
  <body>
    <h1>Hardi's Task Analyzer</h1>

    <div ng-controller="ToddlerCtrl">
      <h2>Toddlers</h2>

      <!-- Add new task form -->
     <label>Add Task Name</label><input type="text" ng-model="empName">
      <label>Add Priority</label><input type="text" ng-model="empCity">
      <label>Add Status</label><input type="text" ng-model="empState">
     <button ng-click="addEmp()">Add <i class="icon-plus"></i></button>
      <br /><br />
      {{empName}}

      <table>
        <tr>
          <th>Task Name</th>
          <th>Priority</th>
          <th>Status</th>
        </tr>
        <tr ng-repeat="task in tasks">
          <td>{{task.task}}</td>
          <td>{{task.priority}}</td>
          <td>{{task.status}}</td>
        </tr>
      </table>
    </div>
  </body>

</html>

For an updated view of these changes, please visit the following Plunker link: http://plnkr.co/edit/pMCFSilYUC1QHH6FUl6G?p=preview

Once implemented, these modifications will ensure the tasks are added to both the list in the view and controlled by the controller. To update the JSON file, you'll need to incorporate server-side actions using technologies like NodeJS, ASP.NET, Java, or Ruby. A save button should be included to send the updated list to the server for JSON file updates. It's recommended to utilize a database instead of a JSON file for efficient concurrency management.

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

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...

What steps can I take to troubleshoot a non-functional button in a Bootstrap 5 Modal?

I have a Django based web site that utilizes Bootstrap 5 for styling. Among the data presented on the site is a table with a notes column containing lengthy text. To enhance readability and keep the table compact, I attempted to integrate the Bootstrap Mod ...

Encountering a syntax error close to an unexpected token '../lib/cli.js' while attempting to launch an application through pm2 start

I'm encountering an issue while executing pm2 start with an ecosystem.config.js /root/.nvm/versions/node/v18.16.0/bin/npm: line 2: require('../lib/cli.js')(process)' /root/.nvm/versions/node/v18.16.0/bin/npm: line 2: syntax error near u ...

Mastering the Art of Modifying HTML with Node.js

Is it possible to manipulate HTML using Node.js? 1. First, I need to retrieve data from a database. 2. Then, I need to modify or add HTML code within Node. In essence, the goal is to fetch data and integrate it into an HTML file. The JavaScript snippet ...

Displaying numerous Google charts within a Bootstrap carousel

A bootstrap carousel has been implemented to showcase our company's data. The carousel includes a bootstrap table, images, and two Google charts: a pie chart and a stacked bar chart. The issue arises when the active class is not maintained for the Go ...

Reacquire Angular Range

My table is displaying all the data, and I have applied the tablesorter plugin after binding the table. However, after applying the plugin, ng-click is not working for the table. I suspect that this issue is related to the plugin's scope object not ...

What is the best way to establish a two-way connection between two arrays?

Within my application, there is an ItemsService responsible for fetching Items from the server and storing them as JSON objects in its cache. These Items may be displayed in various formats such as tables, graphs, or charts. For instance, when setting up ...

The HTML code for the base64 image conversion failed to load

I am facing an issue with handling HTML strings containing base64 image tags generated by Summernote. I have a process in place where I load the image elements, convert them to image blobs, upload them to get the image-url, and then update the src attribut ...

Using a custom filter in AngularJS ui-grid for efficient re-use

I've set up a basic grid with multiple columns, some of which display ranges like 10 - 50 and 0 - 9. I created a custom filter for one of the columnDefs: filter: { condition: function(searchTerm, cellValue) { ... } } The filter is working perfectl ...

Using JSON data to populate a select menu in AngularJS using the ng-options directive

UPDATE: I have successfully resolved my issue. Thanks for the assistance, everyone. I am working with an array of JSON objects that are structured like so: [{"id":"id1", "text":"text1"}, {"id":"id2", "text":"text2"},....] My goal is to populate an Angul ...

Bring in a php script containing numerous dependencies by utilizing ajax to load the content

I have been attempting to load a PHP file through AJAX using the load() method. Here is the code I am using: var loadUrl = "myfile.php"; $("#lst-results").load(loadUrl); The above code works fine for me, but now I need to inc ...

Automatically Trigger Knex.JS Updates

Utilizing the migration tools provided by Knex.JS, I am attempting to create a table with an automatically updating column named updated_at whenever a record is modified in the database. Take, for instance, this table: knex.schema.createTable('table ...

Error message: "Uncaught TypeError: Cannot read property 'module' of undefined when using AngularJS in conjunction with RequireJS."

Embarking on my journey of app development with angularJS was a thrilling experience. However, after investing weeks into the project, I had an epiphany - why didn't I start using require JS from the get-go to load my modules? A rookie mistake, yes, b ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...

Accessing XML content within a web browser

I am facing an issue with parsing a string in JavaScript. var output = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><abc><xyz><xyzResponse><URL>http%3A%2F%2Flocalhost%3A8080%2Fnet%2Fxyz.do%3Fpartner%3Ddummy%26 ...

Performing an automated check on user messages every 60 seconds using JQuery and Ajax

I am in the process of developing a website with notification features, and I am looking to implement a script that will check for new messages every 60 seconds. The goal is to pass the user id through the script to trigger an alert (currently using a ba ...

How can I stretch a background image using jquery to cover the entire document instead of just the window

I have implemented a plugin called https://github.com/srobbin/jquery-backstretch to effectively stretch the background image. The problem arises when the content of the page is long enough to create a scrollbar. In this case, while scrolling, the backgrou ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...

Can I substitute custom tags for the traditional <p> tag?

My HTML with CSS has an issue where a custom HTML tag is not displaying the text while my CSS picks up another tag. Interestingly, replacing <title>Layout Controls</title> with <p>Layout Controls</p> resolves the problem and shows t ...

When the onclick event is triggered, it leads to the execution

Currently, I am developing a demonstration movie application where I have implemented onclick events using a function to retrieve movie-related data. However, I am encountering an issue when clicking on the specific links I need to work with, as it returns ...