0

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()
                      }
                  }
              }
            ]
        });

    };
})
1
  • JSON.stringify won't show methods defined on the object, and custom objects can define custom toJSON() methods to control how they are serialized. You're better off doing console.log($scope.formUser) and inspecting the whole object. Commented Nov 18, 2016 at 18:38

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.