2016-11-18 59 views
0

我試圖圍繞JavaScript對象包圍我的頭,並努力看到兩個對象是如何不同。AngularJS對象差異

我有添加記錄到數據庫和控制器,使用$ resource $ save()添加記錄的輸入表單。

在我顯示輸入表單之前,如果我定義了這樣的表單對象$scope.formUser = new Users(); $ save的作品。

如果我定義表單對象IKE在此$scope.formUser = {};的$節省給了我這個錯誤:$scope.formUser.$save is not a function

如果我做console.log(JSON.stringify($scope.formUser));這兩個對象看起來完全一樣對我說:

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

爲什麼一個對象保存而另一個不存在?

是否可以創建一個對象而不使用$scope.formUser = new Users();

這裏是我的代碼...

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

    }; 
}) 
+0

JSON.stringify不會顯示在對象上定義的方法,自定義對象可以定義自定義的toJSON()方法來控制它們的序列化方式。你最好使用'console.log($ scope.formUser)'來檢查整個對象。 –

回答

0

當您返回的資源,它返回一個資源對象,它具有$save作爲屬性。做$scope.formUser = {}正在創建一個空對象。