Valentin Garcia Valentin Garcia - 9 days ago 5
JSON Question

Add data to JSON file

With a form, I want to add data to my JSON file. How can I do that ? Do I need to recreate a JSON file or can I add data to my existing JSON file ?

The $http.post doesn't work so it's a bad use of it or I need to replace it ?

HTML File

<body ng-app='app'>
<div ng-init="getData()" ng-controller="listController">
<ul ng-repeat="detail in details">
<li>
<a href="{{detail.url}}">{{detail.url}}</a>
</li>
<li>
{{detail.description}}
</li>
<li>
{{detail.author}}
</li>
</ul>
<form method=POST ng-submit="submit()">
<label for="lien">Lien :
<input type="url" id="lien" ng-model="detail.url" placeholder="http://"/>
</label>
{{detail.url}}
<br><br>
<label for="description">Description :
<textarea id="description" ng-model="detail.description"></textarea>
</label>
{{detail.description}}
<br><br>
<label for="auteur">Auteur :
<input type="text" id="auteur" ng-model="detail.author"></input>
</label>
{{detail.author}}
<p>{{detail}}</p>
<input type="submit" id="submit" value="Submit" />
<p>{{details}}</p>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="script.js"></script>
</body>


JS File

var app = angular.module("app", []);
app.controller("listController", ["$scope","$http",
function($scope,$http) {
$scope.getData = function()
{
$http.get('youtube.json').then(function (response){
$scope.details = response.data;
});
};
$scope.submit = function()
{
$scope.details.push($scope.detail);
$http.post('youtube.json', $scope.details);
}
}]);


JSON File

[
{
"url": "https://www.youtube.com/watch?v=E1NIJjTYq6U",
"author": "Grafikart.fr",
"description": "Salut tout le monde"
},
{
"url": "https://www.youtube.com/watch?v=fOuKMuaGJ54&list=PLjwdMgw5TTLUDlJyx4yIPQjoI-w-7Zs1r",
"author": "Grafikart.fr",
"description": "Les directives"
}
]

Answer

The file is statically served on a server, and that is why you can call $http.get('youtube.json') and have access to it. So, the server provides a URL for you to access it. To actually write to it, you still need a server who will handle the request, and write to the file (if its nodejs with the 'fs' module). Other than that, you cannot access the file system from web :) I hope this helps clarify things.