AngularJS Paging with $location.path but no ngView

2020-01-23 16:36发布

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!

7条回答
虎瘦雄心在
2楼-- · 2020-01-23 17:36

You should be loading $location via Dependency Injection and using the following:

$scope.apply(function () {
    $location.path("yourPath");
}

Keep in mind that you should not use hashtags(#) while using $location.path. This is for compability for HTML5 mode.

查看更多
登录 后发表回答