在角度术语中,“搜索”仅指 URL 的查询字符串参数部分。例如:?key=value&page=42
“路径”指的是没有该查询字符串的 URL。这里/products/page/2
是一条路径。
设置时reloadOnSearch: false
你告诉 Angular 不要重新加载视图和关联的控制器only查询字符串参数发生变化。
- 因此,如果路径发生变化,例如您从
/products/page/2
to /products/page/3
,那么视图仍然会重新加载。不$routeUpdate
将被解雇,因为没有必要这样做。您将从中获得新参数$routeParams
当再次调用控制器初始化函数时。
- 但是,如果路径没有更改,但只有查询字符串参数发生更改。例如,当您从
/products?page=2
to /products?page=3
。那么视图将不会被重新加载并且$routeUpdate
将被广播。
所以这里的解决方案是定义page
作为查询字符串参数而不是路径参数:
angular.module('app.products', ['ngRoute', 'ngResource'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/:section', {
templateUrl: 'tpl/table.html',
controller: 'ProductsCtrl',
controllerAs: 'productsCtrl',
reloadOnSearch: false
});
}])
.controller('ProductsCtrl', ['$scope', '$routeParams', '$location', ProductsCtrl]);
控制器:
function ProductsCtrl($scope, $routeParams, $location) {
$scope.setupView = function setupView(section, page) {
// Setup you view here
// ...
};
$scope.$on('$routeUpdate', function () {
// This is called when only the query parameters change. E.g.: ?page=2
$scope.setupView($routeParams.section, $routeParams.page)
});
// This one is called when the the path changes and the view is reloaded.
$scope.setupView($routeParams.section, $routeParams.page)
}