希望使用Angular将表单中的数据作为JSON数组中的新对象提交

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

本文关键字:新对象 数组 提交 对象 JSON Angular 表单 希望 数据      更新时间:2023-09-26

我希望创建一个带有提交按钮的简单输入框,该按钮将向JSON文件添加信息。我使用Angular来检索数据,创建一个新的JSON对象,并将这个对象和新数据发布到一个名为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,
                    }
                });
        }
      }

});

我不完全明白这是怎么回事。如果您对如何完成这项简单任务有任何见解或指导,我们将不胜感激:)

这不是"$http"的正确实现,"url"属性是接收数据的服务器端点,因此您需要一些服务器端代码来附加到.json文件。

如果您想将信息保存到用户本地,那么LocalStorage API可能就足够了,并且很容易实现