更新问题
标题中的问题仍然存在 – 是否可以捕获?参数并取消视图重新加载.
原来的问题:
我需要为我的应用程序添加锚点支持(锚点到主题).
这是我有多远:
- angular.module('app.topics',[
- 'ui.state','ui.router','restangular'
- 'app.topics.controllers'
- ])
- .config(function config($stateProvider) {
- $stateProvider.state('viewtopic',{
- url: '/topics/:slug?section',onEnter: function($stateParams) {
- // Works,as state has been reloaded.
- console.log('$stateParams',$stateParams);
- },resolve: {
- topic: function ($stateParams,Topic) {
- // Wrapper around Restangular. Returns promise.
- return new Topic().get($stateParams.slug);
- }
- },views: {
- 'main': {
- controller: 'TopicCtrl',templateUrl: 'topics/templates/details.tpl.html'
- },'sidebar': {
- controller: 'SidebarCtrl',templateUrl: 'topics/templates/sidebar.tpl.html'
- }
- }
- });
- });
- angular.module('app.topics.controllers',[])
- .controller('TopicCtrl',function ($scope,topic,$rootScope,$location,$anchorScroll,$stateParams) {
- $scope.topic = topic;
- $scope.slug = $stateParams.slug;
- $scope.section = $stateParams.section;
- // ..
- $scope.$watch('$stateParams.section',function (newValue,newValue) {
- // Does not work.
- console.log('stateParams.section changed',newValue,newValue);
- });
- });
我的根本问题是当我点击链接#/ topics / slug-name?section = section-1,状态被完全重新加载,然后重新请求Topic的数据.如何才能“刷新”查询参数(并在控制器中捕获该事件),但是不要重新加载状态(保持数据加载)?
编辑
对于我的问题,有一个相当简单的解决方案,我没有注意到 –
每个AngularJS documentation在“Hashbang和HTML5模式” – 最后一个哈希可以通过$location.hash()访问,滚动可以由$anchorScroll()发起,
所以我目前的解决方案是:
在控制器中:
- $scope.$watch('$location.hash',function () {
- _.defer($anchorScroll);
- });
需要延迟,因为内容可能尚未被解析,并且没有id.
在模板中,我只需要将目标设置为#/ topics / slug-name#section-name.
你在路由定义中尝试过reloadOnSearch参数吗?
- {
- route:'/',resolve: {
- templateUrl:'template.html',reloadOnSearch: false
- }
- },