Reputation: 1903
So I'm trying to $save an object and empty it's values after.
I've got:
$scope.newObject = new ObjectService()
$scope.saveObject = function(objectToSave)
so ng-click="saveObject(newObject)
calls the function passes the object and then I'm trying to empty it's values after $save is done. The way I want to do it is initialise the objectToSave
into a new ObjectService()
again (as it was before $save()). The problem is that it just doesn't work (I know this probably has to do with Javascript fundamentals, I just don't know what it is).
Please check the code snippet bellow. The code comments explain my issue better.
Please note ! : I'm trying to handle the response of $save in .error() function because this is an example.
angular.module('app', ['ngResource'])
.controller('ctrl', ['$scope', 'ObjectService',
function($scope, ObjectService) {
$scope.newObject = new ObjectService();
$scope.newObject.foo = 'something';
$scope.saveObject = function(object) {
object.$save(function() {
// won't success in this example..
}, function() {
//object.foo = '...'; // This works fine.
object = new ObjectService();
// $scope.newObject shouldn't be a new ObjectService now? So $scope.newObject.foo should be an empty string
});
};
}
])
.factory('ObjectService', ['$resource',
function($resource) {
return $resource('http://somewhere/something', {
foo: '@foo'
});
}
]);
<html ng-app="app">
<body ng-controller="ctrl">
<input type="text" ng-model="newObject.foo">
<button type="button" ng-click="saveObject(newObject)">Save</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-resource.min.js"></script>
</body>
</html>
Upvotes: 0
Views: 68
Reputation: 782
object = new ObjectService();
Won't work because the way that arguments are passed to functions in Javascript. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
In your case, you can assign to $scope.newObject a new empty object.
$scope.newObject = new ObjectService();
You don't even need the argument because you can use the variable $scope.newObject to call resource methods.
Upvotes: 1