I'm trying to get an understanding of AngularJS using $resource, however most of the examples I see out there don't explain how to actually create new instances of something using $resource (or how the entire setup should look).
I've posted my code at the bottom of this.
I have the following setup, where posting to '/entry/api' should create a new entry.
The entry object it self has three properties: name, description and id.
i thought that calling
$scope.save(); would do two things:
- Map the input fields as POST data
- make a POST request to the url defined in the $resource (in this case '/entry/api')
Some examples I've seen are manually mapping the data to the resource as such:
var entry = new Entry();
entry.name = $name; // defined in entryController
entry.description = $scope.description; // <-- defined in entryController
entry.$save()
I thought this wasn't supposed to be necessary, as these fields are defined in the html.
This solution results in:
- Defining a model in the backend
- Defining a model in the front end (the entryController
div
)
- Adding the values from the from the entryController
div
to the JS version of the model and then finally saving it.
It might be the way AngularJS works, however I thought that the input fields in the html would automatically be mapped.
Otherwise you have at least 3 places in the code to update if you add or remove a property of your (backend) model.
How are you supposed to use AngularJS along with $resource
to save new objects?
angular.module('entryManager', ['ngResource']);
function pollController($scope, $resource) {
$scope.polls = $resource('/entry/api/:id', {id: '@id'});
$scope.saveEntry = function() {
this.save();
}
}
<html ng-app="entryManager">
... <-- include angularjs, resource etc.
<div ng-controller="entryController">
<input type='text' ng-model="name"><br/>
<textarea ng-model="description" required></textarea><br/>
<button class="btn btn-primary" ng-click="saveEntry()">Save</button>
</div>
question from:
https://stackoverflow.com/questions/16153313/saving-new-models-using-angularjs-and-resource 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…