Saving new models using AngularJS and $resource

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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)