簡體   English   中英

AngularJS表單提交和重定向

[英]AngularJS Form Submit and Redirect

有沒有一種方法可以使用AngularJs提交表單而不使用異步調用? 我希望它的行為就像我在常規的僅HTML表單上單擊“提交”按鈕一樣。

HTML:

<div ng-controller="myController">
    <form id="myForm">
      <input ng-model="handle">
      <button ng-click="submitForm($event)">Submit</button>
    </form>
</div>

目前,我正在做下面的事情。 問題是,我仍然在同一頁面上,然后必須重定向。 但是下一頁的內容取決於表單提交,因此我寧願不在會話中存儲表單提交的內容。

angular.module('myApp').controller('myController', ['$scope', function($scope) {

    $scope.handle;

    $scope.submitForm = function($event) {

        $event.preventdefault();

        var modifiedHandle= $scope.handle + 'handle';

        $http({
            url: '/submit',
            method: 'POST',
            data: {'handle': modifiedHandle }
        }).then(function(response){

           $window.location.href = '/success';

           //The problem of this approach is that the contents of '/success' depends on the form input.
           //I'd rather not have to flash the submitted data to a session. Is there a pure AngularJs way to do this?

        }, function(data, status){});

    }


}]);

如果使用ui-router而不是ngRoute,則可以將對象作為參數傳遞給新狀態。 該參數不會以URL中的查詢字符串結尾。 答案中詳細介紹了這種方法,我已經使用了很多次。 因此,不是使用$ window,而是使用$ state.go。

另外,您還有2個其他選擇。 您可以將對象直接放在$ rootScope上,從而可以從成功頁面的控制器進行訪問。 一般來說,您不想污染您的rootScope,但它會起作用。

我認為最實用的角度方法是創建一個存儲值的服務。 服務是單例,因此,當您設置值時,可以從其他控制器訪問它。 您的服務可能看起來像這樣:

app.service("Store", function() {

    var formObject = {};

    this.set = function(object) {
        formObject = object;
    };

    this.get = function() {
        return formObject;
    };

    return this;
});

然后,在成功提交表單后,您將調用Store.set(yourObject),然后在加載新控制器時可以調用Store.get()返回該值。 文檔中了解有關角度服務的更多信息。

當然,可以將其視為會話,但是如果提供的其他兩個選項都不適合您的需求,則這是一種有角度的方法。

使用Agular Js CLI,您可以通過以下方式重定向成功提交表單上的頁面:

postData(email){
    if(email==""){
      alert('email feild is empty');
      return false;
    }
    else{
      window.location.href = 'https:wwww.google.com';
    }
  }
  • 這里POSTDATA(電子郵件)在電子郵件基本上是在HTML代碼中使用的模型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM