我希望创建一个带有提交按钮的简单输入框,该按钮会将信息添加到 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>
AngularJS
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 可能就足够了,而且很容易实现
关于javascript - 想要使用 Angular 将表单中的数据作为 JSON 数组中的新对象提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728464/