Okay, I'm fairly new to Angular, but I got stuck and it's probably a rather simple solution.
I have a very basic Angular App with a "Page View/Controller" and a "Admin View/Controller" that use the same JSON files to populate data.
Obviously I want to CRUD some elements in the Admin View, and by this I mean, modify my JSON file.
Heres a piece of my JSON file
{
"id": 22,
"title": "",
"section": "expositions",
"text": "2005 : « Ce soir la lune reve » (Casa de Francia et IFAL - Mexico DF)",
"url": "",
"fr": "",
"es": "",
"en": "",
"active": false
},
{
"id": 23,
"title": "",
"section": "expositions",
"text": "2006 : « Ce monde rayonnant » (Espace Triangle - Bruxelles, Belgique)",
"url": "",
"fr": "",
"es": "",
"en": "",
"active": false
}
I got all these elements in my controller's scope
$http.get('http://example.com/js/texts.json').then(function (result){
$scope.texts = result.data;
});
Everything works fine and I'm able to populate my view with ngModel.
<ul class="angular-content">
<li ng-repeat="expo in texts | filter:{section: 'expositions'}">
<h4>
<input type="checkbox" ng-model="expo.active">
<textarea rows="2" cols="124" ng-model="expo.text"></textarea>
</h4>
<h4 ng-show="expo.fr"><a target="_blank" href="{{expo.fr}}">FR</a></h4>
<h4 ng-show="expo.es"><a target="_blank" href="{{expo.es}}">ESP</a></h4>
<h4 ng-show="expo.en"><a target="_blank" href="{{expo.en}}">ANG</a></h4>
</li>
</ul>
Where I'm stuck is when I modify the values of those <textarea>
s and try to update my JSON file.
$scope.saveTexts = function () {
$scope.newTexts = JSON.stringify($scope.texts);
$http({
method: 'POST',
url: 'http://example.com/js/text.json',
data: $scope.newTexts,
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
}
I'm guessing it's a problem of asynchronous calls or the way I'm using JSON.stringify When I console log, my changes won't appear still.
It also doesn't work properly when I try to add an element:
If I use this function in a ng-click, my view will update and add such element, but not in my $scope.texts
$scope.addExpo = function(){
$scope.texts.push({
"id": 35,
"title": "TEST",
"section": "expositions",
"text": "TEST",
"url": "TEST ",
"fr": "",
"es": "",
"en": "",
"active": true
});
Thanks in advance, and sorry for the long post.
You can't save data directly to JSON-file via $http-request. Here is my advice: