我正在使用angularJS v 1.5.6并想知道如何使用$ location.path正确传递表单数据。
这是我的代码页面A:
<form>
...
<button type="submit" ng-click="submit(formData)">submit</button>
</form>
JS:
app.config(['$routeProvider', function ($routeProvider) {$routeProvider
// Home
.when("/", {
templateUrl: "A.html",
controller: "ACtrl"
})
.when("/B/", {
templateUrl: "B.html",
controller: "BCtrl"
})
//fallback url if nothing matches
.otherwise({
redirectTo: '/'
});
}]);
app.controller('ACtrl', function ( $scope, $location, $http) {
$scope.formData = {};
$scope.submit = function() {
$location.path("/B/" + $scope.formData );
};
});
//controller for B page
app.controller('BCtrl', ['$scope', '$routeParams',
function($scope,$routeParams) {
$scope.formData = $routeParams.formData;
}]);
这是一个非常简单的例子,但我无法弄清楚如何解决它:(
点击提交没有任何反应。如果我从$ scope.formData中删除$ scope,我会收到如下错误:错误:formData未定义。
formdata中的术语可用,我使用console.log($ scope.formData)测试它,一切正常。
这是链接plunker:https://plnkr.co/edit/K5zwcmRRyom5HR4a5Q9o
现在唯一的问题是,如何在foreach循环中正确处理选择对象。需要帮助
答案 0 :(得分:1)
不要使用location.path ...
您可以使用服务或使用localstorage(或其他一些浏览器存储机制[sessionStorage,indexdb]。
以下服务方法
app.service("SomeService", function () {
var value = null;
this.set = function (val) {
value = val;
return this;
}
this.get = function () {
return value;
}
})
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
SomeService.set($scope.formData);
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
//Check that the data is present in the SomeService service.
var dataFromACtrl = SomeService.get();
if (dataFromACtrl) {
$scope.formData = dataFromACtrl;
}
})();
})
使用下面的localStrorage,可以是sessionStorage。
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
window.localStorage.setItem("form_data", JSON.stringify($scope.form_data));
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
var dataFromACtrl = window.localStorage.getItem("form_data");
if (dataFromACtrl) {
$scope.formData = JSON.parse(dataFromACtrl);
}
})();
})
注意强>
使用localStorage示例,您需要进行一些清理,在Bctrl中对数据执行任何操作之后,您想要使用以下任一行代码清除localstorage中的条目:
window.localStorage.removeItem("form_data");
delete window.localStorage["form_data"];
答案 1 :(得分:1)
您可以通过创建服务并使用setter / getter来传输变量。 例如:https://plnkr.co/edit/IuTXsVLU7dq3TylfnSYP?p=preview
app.service('TransferService', [function(){
var savedData,
service = {
getData: getData,
setData: setData
}
function getData(){
return savedData
}
function setData(data){
savedData = data
}
return service
}])