【发布时间】:2015-10-21 22:21:51
【问题描述】:
我对 Angular 很陌生,而且我第一次遇到这个明显常见的问题。我已经阅读了所有解释它的主题,但似乎有许多不同的解决方案/黑客,我想知道在这个问题上什么是好的做法。
我有一个简单的多页面应用程序。应用程序的每个页面都有自己的路径。但是每当我点击后退按钮时,路径就会改变,但 ng-view 会变为空白。 我的 url 中几乎没有任何参数,它们大多是简单的页面和几个 /show page 'content/:id'。 当我单独导航到他们自己的路径时,它们可以工作,但是如果我点击后退按钮,浏览器中的路径会发生变化,并且 ng-view => 空白。
我发现似乎有 2-3 种方法可以做到这一点,
每次更改路径时存储上一页的路径并创建一个后退按钮,该按钮将调用将路径更改为上一个 url 的函数,这看起来很糟糕,或者在路径更改时完全重新加载整个页面后退按钮被击中,这似乎很糟糕,但并非不可能,因为只有在按下后退或真正能够使用后退按钮时,浏览器中已经加载了内容,而不必调用似乎很理想的服务器但也许有更好的方法。
你能解释一下“应该怎么做”的方法吗?我真的不想在我的应用程序中得到一个“返回”链接。
我知道你们喜欢代码,但我认为这里没有必要。如果您需要,请随时询问。
一些代码:
angular.module('TestTool',['ngRoute','ng-rails-csrf','ui.bootstrap','ngAnimate'])
.config(function($routeProvider){
$routeProvider.when('/openquestions', {
templateUrl: '/qa-index.html',
controller:'QaController',
})
.when("/openquestions/:id", {
templateUrl: '/qa-show.html',
controller:'QaShowController',
})
.otherwise({ redirectTo: '/' });
});
-
angular.module('TestTool')
.controller('QaShowController',['$scope', '$http','$location','$routeParams', function($scope,$http,$location,$routeParams) {
$http.get('/qaquestions/' + $routeParams.id + '.json').
then(function(response) {
$scope.test = " ok "
$scope.Qdata = response.data;
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.test = " error"
});
}]);
-
angular.module('TestTool')
.controller('QaController',['$scope', '$http','$location', function($scope,$http,$location) {
////////////////////////////////////////////
$http.get('/qaquestions.json').
then(function(response) {
$scope.test = " ok "
$scope.List = response.data;
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.test = " error"
});
//todo $scope.vote = function(id){};
/////////////// Show
$scope.OpenQuestion = function(Id){
var url = '/openquestions/'+ Id
$location.path(url)
$scope.$apply();
};
}]);
我猜我的视图没用,但基本上我是使用 OpenQuestion 函数从我的索引转到我的显示页面。 这只是代码的一个示例,它不是整个应用程序路由,但该部分的行为与网站的其他部分一样。
【问题讨论】:
-
后退按钮应该可以正常工作,开箱即用。如果没有,那么您的代码中存在问题。发布一个完整的最小示例来重现该问题。
-
我已经更新了帖子
标签: angularjs