2016-02-08 18 views
1

我試圖使用以下代碼與服務器通信。

$scope.Save = function() { 
     $scope.loading = true; 

     if ($scope.roleSetupModel.RoleID === "") { 
      // Save 
      //$scope.loading = true; 
      $http.post('/SecurityModule/RoleSetup/AddRole', JSON.stringify($scope.roleSetupModel)) 
       .success(function (response) { 
        $scope.loading = false; 
        $('#addModal').modal('hide'); 
        $scope.BindDataToGrid(); 
        alert("Success"); 
        toastr.success(response.Message); 

       }) 
       .error(function (response) { 
        $scope.loading = false; 
        alert("Fail"); 
        toastr.error(response.Message); 

       }); 

     } 
     else { 
      $http.post('/SecurityModule/RoleSetup/EditRole', 
        JSON.stringify(convArrToObj($scope.roleSetupModel))) 
       .success(function (response) { 
        $('#addModal').modal('hide'); 
        $scope.loading = false; 
        toastr.success(response.Message); 
        $scope.BindDataToGrid(); 
       }) 
       .error(function (data) { 
        $scope.loading = false; 
        toastr.error(response.Message); 
       }); 

     } 
    } 

但我得到有線行爲。該鏈接每次都會被打到,我在那裏放了一個調試器,但是即使在完成請求之前,我的頁面也會被刷新,從而使我的模型變空,而無需輸入成功或錯誤回調。我對承諾對象有一點了解,但沒有意義。我在這裏做錯了什麼?

+2

哪裏'保存()'也會從叫什麼名字?顯示錶單html基礎。聽起來像表格正在通過默認過程提交,並且頁面正在重新加載 – charlietfl

+0

回答

2

我的猜測是,你沒有約束力$scope.Save()<form>ng-submit,並將它由一個提交按鈕觸發,或者如果形式設置了你沒有遵循形式

文檔:

<form name="formScopeName" ng-submit="Save()" novalidate> 

您的$http應該可以正常工作。但是,如果您在表單角度解釋上設置了action,那麼您希望在不使用Ajax的情況下提交併使用默認瀏覽器進程。所以請確保action屬性不存在。

另請注意,沒有理由自行將數據串聯起來。這將在內部由$http自動完成。這可能導致錯誤

您也可以通過$event進行額外保護,然後防止默認。通常這不是必須的。

ng-submit="Save($event)" 

JS

$scope.Save = function (event){ 
    event.preventDefult(); 
    ..... 
+0

絕對可見。謝謝。 –

+0

所以這是它? – charlietfl

+0

我從表單聲明中刪除了ng-submit,並且點擊瞭解決問題的保存按鈕。 –

相關問題