使用 $location.path 但没有重新加载 ngView 的 AngularJS 分页 [英] AngularJS Paging with $location.path but no ngView reload

查看:21
本文介绍了使用 $location.path 但没有重新加载 ngView 的 AngularJS 分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的单页应用程序加载了一个主页,我想展示一系列的想法.每个想法都显示在动画 Flash 容器中,动画显示在想法之间循环.

想法是使用 $http 加载的:

$scope.flash = new FlashInterface scope:$scope,location:$location$http.get("/competition.json").成功(数据)->$scope.flash._init 数据

但是,为了从历史导航和用户体验中受益,我希望更新地址栏以使用 $location 为每个想法显示正确的 URL:

$location.path "/i/#{idea.code}"$scope.$apply()

我在这里调用 $apply 是因为这个事件来自 AngularJS 上下文,即 Flash.我希望保留当前的控制器/视图并且不重新加载视图.这是非常糟糕的,因为重新加载视图会导致整个 flash 对象被丢弃,并且预加载器循环再次开始.

我试过监听 $routeChangeStart 来做一个 preventDefault:

$scope.$on "$routeChangeStart", (ev,next,current) ->ev.preventDefault()$scope.$on "$routeChangeSuccess", (ev,current) ->ev.preventDefault()

但无济于事.如果我能找到一种在更改 $location.path 时覆盖视图重新加载的方法,那么整个事情就会变得很笨拙.

我仍然对 AngularJS 很有感觉,所以我很高兴任何关于如何构建应用程序以实现我的目标的指示!

解决方案

无需更新路径,只需更新带有页码的查询参数.

设置您的路由以忽略查询参数更改:

<代码>....$routeProvider.when('/foo', {..., reloadOnSearch: false})....

并在您的应用程序中更新 $location:

<预><代码>...$location.search('page', pageNumber);...

My single page application loads a home page and I want to display a series of ideas. Each of the ideas is displayed in an animated flash container, with animations displayed to cycle between the ideas.

Ideas are loaded using $http:

$scope.flash = new FlashInterface scope:$scope,location:$location

$http.get("/competition.json")
  .success (data) ->
    $scope.flash._init data

However, to benefit from history navigation and UX I wish to update the address bar to display the correct url for each idea using $location:

$location.path "/i/#{idea.code}"
$scope.$apply()

I am calling $apply here because this event comes from outwith the AngularJS context ie Flash. I would like for the current controller/view to remain and for the view to not reload. This is very bad because reloading the view results in the whole flash object being thrown away and the preloader cycle beginning again.

I've tried listening for $routeChangeStart to do a preventDefault:

$scope.$on "$routeChangeStart", (ev,next,current) ->
  ev.preventDefault()
$scope.$on "$routeChangeSuccess", (ev,current) ->
  ev.preventDefault()

but to no avail. The whole thing would be hunky dory if I could figure out a way of overriding the view reload when I change the $location.path.

I'm still very much feeling my way around AngularJS so I'd be glad of any pointers on how to structure the app to achieve my goal!

解决方案

Instead of updating the path, just update query param with a page number.

set your route to ignore query param changes:

....
$routeProvider.when('/foo', {..., reloadOnSearch: false})
....

and in your app update $location with:

...
$location.search('page', pageNumber);
...

这篇关于使用 $location.path 但没有重新加载 ngView 的 AngularJS 分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆