我试图围绕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()
}
}
}
]
});
};
})
JSON.stringify不会显示在对象上定义的方法,自定义对象可以定义自定义的toJSON()方法来控制它们的序列化方式。你最好使用'console.log($ scope.formUser)'来检查整个对象。 –