Add the contents of `$scope.data` into a JSON object using

I am trying to update a JSON file with data entered in form elements, but I seem to be encountering some issues.

<html ng-app="example">
    <div ng-controller="ListController">
        <form name="myform" ng-submit="addThis()">
            <input type="text" ng-model="model1">
            <input type="text" ng-model="model2">
        </form>
    </div>
</html>

JS:

 var app = angular.module('example', []);
 app.controller('ListController', ["$scope", "$http", function($scope) {
     $http.get("_/js/data.json").success(function(data) {
         $scope.mydata = data;
     });
     $scope.addThis = function() {
         $scope.mydata.push({
              model1:$scope.mydata.keyname1,
              model2:$scope.mydata.keyname2
         });
     };
 }]);

I'm having trouble understanding what's causing the issue. Can someone help?

Answer №1

There are a few things to consider:

Firstly, in your JavaScript code, it appears that you did not properly close one of the functions.

Secondly, it seems like the scope variables were not defined correctly. The $scope does not typically store "name" properties of HTML objects. To reference variables stored in the controller scope from HTML, use curly brackets or certain ng-tags like ng-model.

Additionally, when storing variables in $scope.mydata.somevar, be sure to call them using mydata.somevar.

Here is the corrected JS code:

var app = angular.module('example', []);
app.controller('ListController', ["$scope", "$http", function($scope) { 

 $scope.mydata = { model1: '', model2: ''} ; // initializing the model earlier on (good practice)

 $http.get("_/js/data.json").success(function(data) {
    $scope.mydata.data = data;
 }); // <----- make sure to have correct syntax!

 $scope.addThis = function() {
   $scope.mydata.model1 = $scope.mydata.data.keyname1;
   $scope.mydata.model2 = $scope.mydata.data.keyname2;
 };
}]);

And here is the corrected HTML code:

<html ng-app="example">
     <div ng-controller="ListController">     
         <form name="myform" ng-submit="addThis()">
            <input type="text" ng-model="mydata.model1"> 
            <input type="text" ng-model="mydata.model2"> <!--- Make sure to use mydata.model2! ---->
          </form>
      </div> 
 </html>

Lastly, keep in mind that $http loads things asynchronously. If you want to improve your code structure, consider using q promises for better flow control. Alternatively, you can automatically load the JSON file into the form and have it store the data in $scope.mydata.model1 and $scope.mydata.model2 as soon as it is retrieved.

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

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Exploring JSON data and appending it to an array: How to do it?

This is my code snippet for iterating through the JSON "data": [myObject removeAllObjects]; NSDictionary *dic = jsonData[@"data"]; for (NSArray *ar in dic) { [myObject addObject:ar]; } Below is the NSLog output for myObject: myObject: ( ...

Exploring the concept of utilizing named arguments within Express.js routing

I've searched extensively, but can't seem to find any information on this topic. My goal is to create requests like the following: url/list/message=hello?id=1234 Despite my efforts, I have not come across any resources on how to achieve this us ...

The overflow hidden property does not seem to be effective when used in conjunction with parallax

The issue arises when I attempt to use the overflow hidden property in combination with parallax scrolling. Although everything seems to be working correctly with JavaScript for parallax scrolling, setting the overflow to hidden does not contain the image ...

Guidelines for passing a value to a method within a method using JavaScript

I am currently exploring how jQuery can be used to select an element, retrieve an attribute, and assign it a new value. While I have successfully managed to select the element and extract the attribute, I am facing difficulty in setting the attribute using ...

What steps should be taken in PHP to display a popup when the user input is found to be invalid?

I've been working on implementing a popup in PHP to show if the user enters an existing username, as per our teacher's requirement to use popUp instead of alert. I have set the visibility property of the popup to "Hidden" in CSS; <div class=&q ...

What steps can be taken to create a progress bar in the input field that spans the entire width of its parent div, reaching

I received assistance from a friend in creating this progress bar. Everything seems to be working well, except for the fact that the progress bar is not extending to the full width of the parent div. The new width after each input tag is entered using Java ...

Using ng-bind-html within a ng-repeat loop

Currently, I am working on developing a custom autosuggest feature where a web service is queried with a search term to retrieve a list of suggestions that are then displayed. My main obstacle lies in trying to highlight the matching term within the sugges ...

What is the reason that the attr function fails to function in this particular scenario?

I want to implement a functionality where clicking on an input field clears its value, but I can't seem to make it work. Here is the HTML code: <input id='input' type="text" name="phppostvar" value="clear this"></input> This i ...

Looking for a way to retrieve Instagram data with Python using Selenium, following Instagram's recent API changes? Having trouble locating all entries, as only 12 are showing up?

I am currently working on scraping Instagram using Python and Selenium with the objective of extracting the URL of all posts, number of comments, number of likes, etc. Although I have successfully scraped some data, I have encountered an issue where the p ...

Receive the complete HTML page as a response using JavaScript

When making an Ajax post to a specific page, I either expect to receive an ID as a response if everything goes smoothly, or I might get a random html page with a HTTP 400 error code in case of issues. In the event of an error, my goal is to open the enti ...

Positioning Backgrounds with Padding in DIV Elements

I am trying to figure out how to add a check mark next to text in a button with specific styling. I have managed to get the check mark aligned properly using Background:left center, but I also want to add padding and adjust spacing. Is there a way to achie ...

Codemirror - Advanced Auto-Suggest Feature with Separator

Can a separator be easily added in the hints/autocomplete addon? This separator would help transform the suggestion box to look like: f1 f2 f3 --- var1 var2 ...

Difficulty encountered when utilizing a header-only library within Visual Studio 2022

Having encountered some issues with RapidJSON, a library I was trying to use, I decided to give nlohmann's json library a shot. This library is said to be very user-friendly and easy to implement. To get started, I created a new console project in Vi ...

Making requests using Axios in a web application created with Express, Node, and EJS

I'm currently working on a project that involves using Express.js, node.js, Axios, and ejs. The aim is to make REST calls to Oracle SQL REST services through Axios. However, I am facing challenges when it comes to dealing with Promises or Async/Await. ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

Error 9 in Firebase: The function 'initializeApp' could not be located within the 'firebase/app' module

Since updating to firebase 9, I've been encountering issues with importing certain functions that were working fine on firebase 8. I've gone through the documentation and made necessary code improvements, but the error persists. This issue is not ...

What sets apart loads and dumps from reading a JSON file?

I've got a basic json file named 'stackoverflow.json" { "firstname": "stack", "lastname": "overflow" } What are the differences between the following two functions: def read_json_file_1(): with open('stackoverfl ...

Guide on accessing an array within a JSON object?

I have the following JSON object: [ { "comments": [ { "created_at": "2011-02-09T14:42:42-08:00", "thumb": "xxxxxxx", "level" ...

I encountered a response error code 500 from the development server while using my emulator

As I embark on setting up the react-native environment for development, I encounter an error when executing the command react-native run-android. root@pc:~/l3/s2/DevMobMultipltm/Wakapp# ` A series of tasks are carried out including scanning folders for sy ...