【问题标题】:AngularJS successful PUT followed by unwanted GETAngularJS 成功 PUT,然后是不需要的 GET
【发布时间】:2014-12-23 16:08:05
【问题描述】:

总之,在我的 AngularJS 页面中,我 PUT 并接收答案。现在 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, 杰罗姆。

【问题讨论】:

  • 它不是有角度的,它只是你的 HTML。提交按钮即使被ng-click装饰,仍然会提交。

标签: javascript angularjs put


【解决方案1】:

您正在使用 ng-click,但没有什么可以阻止按钮的默认操作,即提交表单。

请改用以下内容。

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

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

【讨论】:

  • 糟糕...我以为我从该按钮中删除了 type="submit" 。正如你所说,我改变了它,我得到了完美的结果。感谢您的关注!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多