javascript - AngularJS 成功 PUT 后进行不需要的 GET

标签 javascript angularjs put

总之,在我的 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>

我的 Controller 是:

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() 被调用,并且(使用调试器)调用 .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"

关于javascript - AngularJS 成功 PUT 后进行不需要的 GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27623941/

相关文章:

javascript - 为什么图像不显示? "skrivut"有什么问题

javascript - 如何在我们的网络应用程序中创建我们自己的通知(例如 Facebook)

javascript - Jquery 数据表 : sort number with comma doesn't work

javascript - 从两个表达式设置 ng-checked 值

javascript - 如何使用自定义服务将 LinkedIn API 中的用户信息保存到 Angularjs Controller 中

java - 如何修复 "the method put(string, string) is undefined for the type string"?请

scala - 将元素添加到 scala.collection.mutable.Map 的语法是什么?

javascript - 显示 sparql 查询结果的问题

javascript - AngularJS html 绑定(bind)和 Chome 应用程序 CSP

javascript - 在 Node.js 中使用 PUT 删除