2016-07-18 13 views
1

舉例來說,在Views/Index.cshtml下,我有一個輸入表單,只要輸入一次,一旦填寫並提交,就會經過控制器js文件中的一個函數,然後window.location.pathname重定向到另一個頁面。該下一頁與另一個控制器/ js文件相關聯。如何在ASP MVC設置中將AngularJS中的變量從一個控制器傳遞到下一個?

如何將一對變量從一個傳遞給另一個?

我試着做這種方式,它不工作:

一次嘗試

_Layout.cshtml

<html ng-app="MIScheduler"> 
    <head> 
     ... 
    </head> 
    <body> 
     @RenderBody() 

     // AngularJS scripts 
     <script src="app.js"></script> 
    </body> 
</html> 

Index.cshtml

<input ng-model="userID" name="userID" /> 
<input ng-model="userEmail" name="userEmail" /> 
<input type="submit" id="submit" /> 

@section scripts { 
    <script src="HomeController.js"></script> 
} 

HomeController.js

var CID = null; 
var Email = null; 

$scope.submit = function() { 
    CID = $scope.userID; 
    Email = $scope.userEmail; 
    window.location.pathname = 'Home/OtherPage'; 
}; 

然後,當重定向到OtherPage.cshtml

{{cid}} 
{{email}} 

@section scripts { 
    <script src="OtherPageController.js"></script> 
} 

不輸出任何東西,如果我OtherPageController.js

$scope.cid = CID; 
$scope.email = Email; 

我也試過在app.js實現服務和傳遞對兩個控制器的服務,但沒有輸出這種方式。

第二次嘗試

這裏是我的第二個方法我試過:app.js

angular.module('moveinScheduler', []) 
    .service('ShareUserInfo', function() { 
     LData = { 
      cid: '', 
      email: '' 
     } 

     return { 
      getValues: function() { 
       return LData; 
      }, 
      setValues: function (cid, email) { 
       LData.cid = cid; 
       LData.email = email; 
      } 
     }; 
    }); 

Index.cshtml同上。 HomeController.cshtml

var CID = null; 
var Email = null; 

$scope.submit = function() { 
    ShareUserInfo.setValues(d.data.CID, d.data.Email); 
    window.location.pathname = 'Home/OtherPage'; 
}; 

OtherPageController.js

$scope.values = ShareUserInfo.getValues(); 

OtherPage.cshtml

{{values}} 

沒有正在輸出。記住兩個控制器,我將ShareUserInfo作爲服務擴展傳遞給函數。

有什麼不對?爲什麼我的值沒有被存儲/傳遞?

+0

所以你不要有一個單頁的應用程序?你可能可以將查詢字符串中的變量傳遞給其他人@PageHtml – Maccurt

+0

@Maccurt我試圖避免查詢字符串選項與傳遞的電子郵件有關。 – NoReceipt4Panda

回答

1

可以在Window.localStorage保存數據:

HomeController.js:

angular.controller('ExampleController', function($scope) { 
    $scope.submit = function() { 
     var obj = { 
      cid: $scope.userID, 
      email: $scope.userEmail 
     }; 
     localStorage.setItem('data', JSON.stringify(obj)); 
     // Make your redirect 
    }; 
}); 

PageController.js:

angular.controller('PageController', function($scope) { 
    var data = JSON.parse(localStorage.getItem('data')); 

    console.log('data: ', data); 
}); 
+0

需要放置[['ngStrorage']'在所有包含'app.js'的js文件中? – NoReceipt4Panda

+0

我已經刪除了對'ngStorage'的依賴,使其更容易。現在你可以直接在'localStorage'中保存數據。 –

+0

我有一個問題,我完全按照上面的代碼狀態進行。在'HomeController.js'中,一旦執行_ $ localStorage未定義的函數,我會收到一個錯誤。但如果我把'$ localStorage'放入'...('HomeController',函數($ scope,$ localStorage)..'代碼中斷,我得到_Error:$ injector:unpr Unknown Provider_ – NoReceipt4Panda

0

由於您沒有使用單頁應用程序,並且您避免使用查詢字符串,因此您可以使用$ http.post並將視圖模型對象傳遞到您的OtherPageController。在OtherPageController中,實現一個[HttpPost]操作方法,該方法接受從您的$ http.post調用傳入的視圖模型對象。

相關問題