[英]Ng-submit called twice with Routeprovider
我使用相同的form
在數據庫中創建和更新用戶。 我可以正確更新,但是當我創建一個用戶時,提交兩次發送並在數據庫中創建兩個相同的用戶。
我在RouteProvider
有這個。
.config(function($routeProvider) {
$routeProvider
.when("/users", {
controller: "MainControlador",
templateUrl: "templates/users.html"
})
.when("/user/:id", {
controller: "UserControlador",
templateUrl: "templates/user.html"
})
.when("/users/edit/:id", {
controller: "UserControlador",
templateUrl: "templates/form.html"
})
.when("/users/new", {
controller: "NewUserControlador",
templateUrl: "templates/form.html"
})
.when("/", {
templateUrl: "templates/main.html"
})
.otherwise("/");
})
這是我的form
<div>
<form ng-submit="saveUser()">
<input ng-model="user.name" type="text" required>
<input ng-model="user.surname" type="text" required>
<input ng-model="user.phone" type="text"required>
<input ng-model="user.email"type="text" required>
<input type="submit">
</form>
</div>
最后我用這個controller
//Controller Update
.controller("UserControlador", function($scope, $routeParams, UserAPI) {
$scope.title = "Edit user";
UserAPI.getOne($routeParams.id).success(function(data) {
//Get Array First Element
$scope.user = data[0];
})
$scope.saveUser = function() {
var data = ({
id: $routeParams.id,
name: $scope.user.name,
surname: $scope.user.surname,
phone: $scope.user.phone,
email: $scope.user.email
});
UserAPI.update(data).success(function(data) {
$scope.user = data;
})
}
})
//Controller Create
.controller("NewUserControlador", function($scope, UserAPI) {
$scope.title = "Add user";
$scope.saveUser = function() {
var data = ({
name: $scope.user.name,
surname: $scope.user.surname,
phone: $scope.user.phone,
email: $scope.user.email,
});
UserAPI.create(data).success(function(data) {
console.log(data);
$scope.user = data;
})
}
})
¿任何想法在這里會發生什么? 我嘗試使用console.log,但顯然一切正常。 我嘗試使用Angular batarang來調試角度調用,但不起作用。
一個非常愚蠢的錯誤。 在我的PHP代碼中,我有這個...
<?php
$conexion = new PDO("mysql:host=localhost;dbname=httpcrud;charset=utf8", "root", "");
$userName = $_GET['userName'];
$userSurname = $_GET['userSurname'];
$userPhone = $_GET['userPhone'];
$userEmail = $_GET['userEmail'];
$sql=$conexion->query("INSERT INTO users (name,surname,phone,email) VALUES('$userName','$userSurname','$userPhone','$userEmail')");
$json = json_encode($sql->execute());
echo $json;
?>
當我使用$sql->execute()
和query()
時,提交重復insert
。 我刪除$json= json_encode($sql->execute());
到$json = json_encode($sql)
,最后一切正常。
您已經聲明了兩個控制器,一個用於保存用戶( NewUserControlador ),一個用於更新(UserControlador) 。 這兩個方法都稱為saveUser(),它們在$ scope上聲明。
由於名稱相同,可能存在沖突。 您為什么不使用一個控制器進行這些操作? 畢竟,它們都是針對同一實體(用戶)的所有CRUD操作。
如果仍然要使用兩個不同的控制器,則可以使用一些日志記錄來查找正在發生的事情,或者更大的主意是在UserControlador中重命名更新方法。
可以在這里找到有關范圍的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.