angularjsobjectangular-resource

AngularJS object differences


I'm trying to wrap my head around JavaScript objects and am struggling to see how two objects are different.

I have an input form for adding records to a database and a controller that does the adding using $resource $save().

Before I show the input form, if I define the form object like this $scope.formUser = new Users(); the $save works.

If I define the form object ike this $scope.formUser = {}; the $save gives me this error: $scope.formUser.$save is not a function

If I do console.log(JSON.stringify($scope.formUser)); both objects look exactly the same to me:

$scope.formUser = new Users(); shows {"firstname":"aaa","lastname":"bbb"} $scope.formUser = {}; shows {"firstname":"aaa","lastname":"bbb"}

Why does one object save and the other one doesn't?

Is it possible to create an object that will work without using $scope.formUser = new Users();?

Here's my code...

angular.module('starter.services', [])

.factory('Users', function ($resource) {
    return $resource('https://example.com/:id', { id: '@id' }, {
        update: { method: 'PUT' }
    });
})


.controller('myController', function ($scope, $ionicPopup, Users) {

    // Triggered by clicking the 'add user' button in header.html
    $scope.addUser = function () {

        //$scope.formUser = {}; // this doesn't work
        $scope.formUser = new Users(); // this works

        // Show popup form
        $ionicPopup.show({
            templateUrl: 'templates/userform.html',
            title: 'Add new user',
            subTitle: 'Firstname is mandatory',
            scope: $scope,
            buttons: [
              { text: 'Cancel' },
              {
                  text: '<b>Save</b>',
                  type: 'button-positive',
                  onTap: function (e) {
                      if (!$scope.formUser.firstname) {
                          e.preventDefault(); // Prevent save if first name is empty
                      } else {
                          $scope.formUser.id = 0; // If id is left undefined, $save sends a GET method
                          $scope.formUser.$save()
                      }
                  }
              }
            ]
        });

    };
})

Solution

  • When you return the resource, it returns a resource object, which has the $save as a property. Doing $scope.formUser = {} is creating an empty object.