我有一个包含对象数组的json文件,我想知道$ http post方法将另一个对象添加到这个json(包含对象数组)。假设同一文件夹中的所有3个文件。这必须在angularjs中完成。请帮助&如有任何其他细节,请询问。干杯!
- contact_details.json ---
[{
"name": "Darshil Patira",
"number": "9829038347",
"image": "images/dawn_scenic.jpg",
"email": "darshilpatira@gmail.com"
}, {
"name": "Sujith V",
"number": "9756423129",
"image": "images/blue_ocean.jpg",
"email": "sujithv@gmail.com"
}]
--- --- addcontact.html
<div class="form-style">
<div class="form-style-heading">
Provide your information
</div>
<form name="reviewForm" action="" ng-submit="addcontact()" ng-controller="addContactController">
<label for="field1">
<span>Name<span class="require">*</span>
</span>
<input type="text" class="input-field" name="field1" ng-model="name" required />
</label>
<label for="field2">
<span>Email<span class="require">*</span>
</span>
<input type="text" class="input-field" name="field2" ng-model="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required />
</label>
<label for="field3">
<span>Telephone<span class="require">*</span>
</span>
<input type="text" class="tel-number-field" name="field3" ng-model="number" pattern=".{5,10}" required />
</label>
<input type="file" name="pic" accept="image/jpg">
<label>
<span> </span>
<input type="submit" value="Submit" />
</label>
</form>
</div>
--- app.js(控制器)---
var app = angular.module("mainApp", ['ngRoute']);
app.controller('addContactController',function($scope,$http){
var dataobj = { 'name':$scope.name, 'email': $scope.email, 'number':$scope.number };
$http.post('contacts_details.json',dataobj);
});
答案 0 :(得分:0)
Angular不知道如何写入文件系统。由服务器决定将HTTP请求解释为数据库/持久性调用。
示例:
.controller('someCtrl', function($http){
var baseUrl = ... ;
$scope.doPost = function(){
$http.post(baseUrl + '/resource', {param1: 1, param2: 2});
}
});
//In server (NodeJS?)
var fs = require('fs'); //File system module
server.post('/resource', function(request, response){ //Every HTTP post to baseUrl/resource will end up here
console.info('Updated myJSON.json');
fs.writeFile('myJSON.json', request.body, function(err){
if(err) {
console.error(err);
return response.status(500).json(err); //Let the client know something went wrong
}
console.info('Updated myJSON.json');
response.send(); //Let the client know everything's good.
});
});
答案 1 :(得分:0)
如果您只需要为开发服务.json,您可以尝试json-server。这是一个快速简便的选择 - 非常适合开发,您无法访问服务器但仍需要/可以通过api使用json数据。