AngularJS成功的PUT之后是不需要的GET



总之,在我的AngularJS页面中,我放置并接收答案。 现在,Angular正在做一些事情,将表单字段放在URL中,并执行相当于GET的操作。

详细地说,我的表格是这样的:

<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>

我的控制器是:

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

当我调用页面时:

http://MYAPP/sg/user/edit/2

页面显示正确,填充了用户 #2 数据。 当我单击"提交"时,$http.put() 被称为 OK,并且(使用调试器)调用 .success() 函数,"数据"被填充我的"用户 #2 更新确定"消息。

一旦 success() 退出,URL 栏就会填充以下内容:

http://MYAPP/sg/user/edit/2?userName=SecondUser&fullName=Second+User

并再次调用 .controller()。 好像页面被告知要刷新,除了表单字段被填充,就像我发出 GET 一样。

我在这里错过了什么?

TIA,杰罗姆。

您正在使用 ng-click,但无法阻止按钮的默认操作,即提交表单。

请改用以下内容。

<form ng-submit="submitForm()" ...>

或者将按钮的type="submit"更改为 type="button"

最新更新