Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving new models using AngularJS and $resource

Tags:

angularjs

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:

  1. Map the input fields as POST data
  2. 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:

  1. Defining a model in the backend
  2. Defining a model in the front end (the entryController div)
  3. 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>
like image 818
Jones Avatar asked Apr 22 '13 17:04

Jones


People also ask

What is $resource in AngularJS?

Overview. A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service. Requires the ngResource module to be installed.

Which method is used to create models in AngularJS?

In basic examples, AngularJS uses the $scope object as the model. However, in the previous article I showed how using the controllerAs method allowed the controller itself to be added to the scope with a given name and essentially be used as the model.


2 Answers

The first think you should note, that scope != model, but scope can contain model(s).

You should have some object in your scope and then save it.

So, there would be something like the following:

HTML:

<div ng-controller="entryController">
    <input type='text' ng-model="poll.name"><br/>
    <textarea ng-model="poll.description" required></textarea><br/>
    <button class="btn btn-primary" ng-click="saveEntry()">Save</button>
</div>

JavaScript:

function pollController($scope, $resource) {
    var polls = $resource('/entry/api/:id', {id: '@id'});

    $scope.saveEntry = function() {
        polls.save($scope.poll);
    }
}

Note1: even if you do not have initialized poll object, AngularJS will automatically create new object when you start typing.

Note2: its better to wrap your form into ngForm (by adding ng-form="someformname" attribute to div with ng-controller or wrap with <form name='...'>..</form>. In this case you could check validity of form by $scope.someformname.$valid before saving.

Good example is on main page of AngularJS web site under "wiring the backend" section (btw, mine favorite).

like image 105
Valentyn Shybanov Avatar answered Oct 16 '22 09:10

Valentyn Shybanov


Don't use save method over model object itself, use save method of model class, For example -

//inject User resource here
$scope.user = new User();

$scope.user.name = "etc";

User.save($scope.user,function(response){

});

previously i was using $scope.user.$save(function(response){}) it was clearing my $scope.user object

like image 37
vivex Avatar answered Oct 16 '22 10:10

vivex