我正在尝试以模态向已经在我的网站上浏览但在新页面上为新用户显示的用户显示相同的内容(具有相同的url)。
例如,这里的用户在树冠上行驶:
转到https://canopy.co/,然后单击链接。内容以模态加载,其URL更新为https://canopy.co/products/12309。但是,直接转到https://canopy.co/products/12309,它以自己的视图加载它,没有模态。
我该如何用angular做到这一点?我用ui-router和多个视图尝试了很多东西,但是最终被渲染了两次。
谢谢你的帮助。
可能有几种方法可以做到这一点。这是我的。
当状态发生变化时,我们要检查是否可以在当前视图中的模式内提供内容,而不是完全替换当前视图。我们将在路由配置中对此进行定义-可以托管模式的视图将带有modalMaster
标志,而可以在模式中显示的视图将带有modalSlave
标志。
我们将使用ui.router
的$stateChangeStart
事件来拦截状态更改,并根据需要取消更改,这是我们打开模式的地方。
请注意,所有代码都在coffeescript和Jade中,我发现它更加整洁。如果您需要转录,请使用js2coffee.org。
.config ($stateProvider, $urlRouterProvider)->
# Add details on which templates can open models containing which other
# templates.
$stateProvider.state 'shop',
url: '/'
templateUrl: 'shop.html'
modalMaster: true
$stateProvider.state 'item',
url: '/item/{id}'
templateUrl: 'item.html'
modalSlave: true
$urlRouterProvider.otherwise('/');
# Enable handling of url changes ourselves.
$urlRouterProvider.deferIntercept()
最后一行很重要,因为它允许我们停止url更改,稍后再更新视图。
.run ($rootScope, $state, $modal, $location, $urlRouter, $timeout)->
# set some flags for use later.
modalInstance = toStatePrevented = entering = null
# Intercept state changes - if we're in a modal master and we're going to a
# modal slave, open a modal containing the slave state instead.
$rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState)->
if fromState.modalMaster and toState.modalSlave
event.preventDefault()
# set a property to show which state is currently in the modal
$state.current.inModal = toState
entering = true # for url handling
$timeout -> # change url manually
$location.path($state.href(toState, toParams), false)
, 0 # the 0 timeout makes sure the preventDefault doesn't stop url
# change
# open a modal containing the new state, you can merge this with
# modal specific properties like "resolve" etc. if you want them
modalInstance = $modal.open(toState)
# clear our flags when the modal closes - this only uses dismiss so we
# only need "catch" right now.
modalInstance.result.catch(()->
modalInstance = toStatePrevented = $state.current.inModal =
entering = null
$state.go(fromState)
)
$rootScope.$on '$locationChangeSuccess', (event, toUrl, fromUrl)->
event.preventDefault()
# if there is nothing in a modal, just handle as normal
if !$state.current.inModal? then $urlRouter.sync()
# dismiss modal if url changes and modal is visible
else if not entering and modalInstance? then modalInstance.dismiss()
# if we are opening a modal, set a flag so that next time the url changes
# we will dismiss it.
else entering = false
评论应解释其中的大部分内容。在实践中,您可能需要的不仅仅是这里的内容,例如,您应该确保正确处理了从模态内部单击链接的情况,但这应该可以帮助您开始。
自然,我在这里演示了此解决方案,但是请确保您使用“在单独的窗口中启动预览”功能来查看所有功能是否全部发挥作用。
从导航shop
到会item
打开模式,但是直接item
通过URL导航到会自动打开项目ui-view
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句