简体   繁体   中英

Want to submit data from a form as a new Object in a JSON array using Angular

I am looking to create a simple input box with a submit button that will add information to a JSON file. I am using Angular to retrieve that data, create a new JSON object and post this object with the new data to a file called pets.json.

HTML

<form ng-submit="submit()" ng-controller="PetPosting">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
</form>

Angular JS

  var app = angular.module('app', ['ui.bootstrap', 'bootstrapLightbox']);

 //load images from pets.json and display them in HTML
 app.controller('GalleryCtrl', function ($scope, Lightbox, $http) {
     $http.get('pets.json')
     .then(function(res){
      $scope.images = res.data;
   });
 });
 /*Add new data to JSON file*/
 app.controller('PetPosting',function($scope, $http) {

      $scope.submit = function() {
        if ($scope.text) {
          $http({
                    method: "post",
                    url: "pets.json",
                    data: {
                      "thumbUrl": $scope.text,
                    }
                });
        }

      }



});

I don't understand fully how this works. Any insight or direction on how to figure out how to do this simple task would be greatly appreciated :)

Thats not the correct implementation of "$http", the "url" property is a server endpoint that receives your Data, for that you would need some server-side code to append to the .json file.

If your wanting to save information Local to the user the LocalStorage API maybe sufficient and is very easy to implement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM