[英]In AngularJS how to redirect from on controller to another?
假設我有一個AngularJS,其狀態/控制器URL為:
url: '/myurl'
在其他控制器中(例如在按下按鈕時),我執行以下操作:
$window.location.href = '/myurl';
跳到另一頁。 但是,是否存在“ AngularJS本機”頁面之間切換的方式?
每個頁面都有$ state,您也可以在各州之間傳輸數據。 使用流動函數來更改狀態,然后將其作為依賴項注入到控制器中。
$state.go('your-new-state', {
...params
});
使用ui路由器。
您可以用不同的方式來做。 取決於您想要什么以及使用哪種路由器:
ng-route
$routeProvider
.when('/main' , {templateUrl: 'main.html'})
.when('/somePage', {templateUrl: 'somePage.html'})
.otherwise({redirectTo: '/main'});
app.controller('myCtrl', function ($location) {
$scope.click = function () {
$location.path('/somePage');
}
});
ui-router
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'main.html'
})
.state('somePage', {
url: '/somePage/:someParam',
templateUrl: 'somePage.html'
});
app.controller('myCtrl', function ($state) {
$scope.click = function () {
$state.go('somePage', { someParam: 'someValue'});
}
});
ui-router
> =版本1.0.0
這顯示了如何處理基於狀態的重定向。 在某些情況下,當您必須根據某些條件在該路由上處理重定向時,這可能會有所幫助。
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'main.html',
redirectTo: (trans) => {
if (trans.params().redirectToSomePage) {
return { state: 'somePage', params: { someParam: 'someValue' } };
}
}
})
.state('somePage', {
url: '/somePage/:someParam',
templateUrl: 'somePage.html'
});
如果您使用的是ngRoute,則可以使用$ location
例如
$location.path('/myurl');
請注意,您必須在控制器中注入$ location
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.