In summary, in my AngularJS page I PUT and receive answers. Now Angular is doing something that puts the form fields in the URL and performing what amounts to a GET.
In detail, my form is like:
<body ng-app="userApp">
<div ng-controller="userController">
<form id="userForm" modelAttribute="userAttribute" action="">
<table>
<tr><td><input type="text" id="userName" ng-model="user.userName" /></td></tr>
<tr><td><input type="text" id="fullName" ng-model="user.fullName" /></td></tr>
<tr><td><button type="submit" ng-click="submitForm()">Submit</button></td></tr>
</table>
</form>
</div>
</body>
And my controller is:
angular.module("userApp", [])
.controller("userController", ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.user = {};
$scope.msg = "";
$http.get('/sg/user/' + userId)
.success(function(data, status, headers, config) {
$scope.user = data;
$scope.error = "";
if(typeof $scope.user._id === "undefined") {
$scope.formTask = "Create New";
$document.prop('title', 'Create User');
} else {
$scope.formTask = "Edit";
$document.prop('title', '"Edit User');
}
})
.error(function(data, status, headers, config) {
$scope.user = {};
$scope.error = data;
});
$scope.submitForm = function()
{
$http.put('/sg/user/' + userId, $scope.user)
.success(function (data, status, headers, config)
{
$scope.msg = data;
})
.error(function (data, status, headers, config)
{
$scope.msg = "SUBMIT ERROR";
});
};
}]);
When I call the page:
http://MYAPP/sg/user/edit/2
the page displays properly, filled with user #2 data. When I click on "Submit" the $http.put() is called OK, and (using the debugger) the .success() function is called, the "data" being filled with my "User #2 updated OK" message.
Once success() exits the URL bar is filled with this:
http://MYAPP/sg/user/edit/2?userName=SecondUser&fullName=Second+User
and the .controller() is called again. As though the page were told to refresh, except that the form fields are filled like I sent out a GET.
What am I missing here?
TIA, Jerome.
You're using ng-click, but there's nothing to stop your button's default action, which is to submit the form.
Use the following instead.
<form ng-submit="submitForm()" ...>
Or change the button's type="submit"
to type="button"
.