Reputation: 2414
I´m learning ngResource.
I can "get" all the values of the json file. But I cannot do it work with one value (with query) and updating other.
I get all with:
this.total = userService.query();
I´m trying to get one with:
this.user = userService.query({"name":"Luis"});
I´m trying to update with:
var userToUpdate = userService.get({},{"name":"Luis"});
userToUpdate.name = "Name changed";
userToUpdate.$save();
Now the general code
file1.html
<div ng-app="module" ng-controller="controls as ctrl">
<div ng-repeat="item in ctrl.total">
<span ng-bind="item.name"></span>
</div>
{{ ctrl.total }}
<br /><br />
{{ ctrl.user }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-resource.js"></script>
<script>
var x = angular.module("module", ["ngResource"]);
x.factory("userService", ["$resource", function($resource)
{
return $resource("data.json");
}]);
x.controller("controls", ["userService", function(userService)
{
this.total = userService.query();
this.user = userService.query({"name":"Luis"});
var userToUpdate = userService.get({},{"name":"Luis"});
userToUpdate.name = "Name changed";
userToUpdate.$save();
}]);
</script>
data.json
[
{"id": 1, "name": "Mario", "lastname": "Perez"},
{"id": 2, "name": "Raul", "lastname": "Alvarez"},
{"id": 3, "name": "Pedro", "lastname": "Tomas"},
{"id": 4, "name": "Luis", "lastname": "Ranks"}
]
Anyone can help me? I´m a novice. Thanks for your time.
Upvotes: 0
Views: 195
Reputation: 7279
JSON is a format to store data. You can store static data in *.json files. So data in your data.json file is static and it is just static storage of some data.
So, when you do userService.get()
with any query-parameters, you will get same response each time. You just getting static data. This data will be returned despite of query parameters
And again. *.json is just static data storage. You can not update it with userService.$save()
method. You will get same static data as response.
To update something you need some service which will update your data. For example, you have some back-end, which is updating data.json.
So, normal case will be:
Code of front end should be:
var module = angular.module('myApp', []);
module.factory('userService', ['$resource', function ($resource) {
return $resource('/api/data/:id');
}]);
module.controller('myCtrl', ['$http', function ($http) {
userService.get(); // GET /api/data request will be performed
userService.put({id: 1}); // PUT /api/data/1 request will be performed
userService.post({name: 'someName'}); // POST /api/data will be performed
}]);
I wouldn't provide backend code. It will manipulate *.json file in your case.
Upvotes: 1