7

I'm trying to update $location.path from within an AngularJS directive. It's not working as I expect, which is to update the URL displayed in the browser window and show different contents on my page. My functions are definitely getting called with the correct values, as seen in the console. I think $location.path might be having some effect, because when I click the link, some additional functions get called that would be called on the new page, only the new page is never displayed. When I use $location.path within a controller, it works as expected, but not in my directive.

Here's the HTML for my directive:

<div detail-link="/comments?post={{post.postId}}" ng-click="clickDetailLink()"></div>

Here's the directive's definition (in CoffeeScript):

directives.directive 'detailLink', ['$location', ($location) ->
    return (scope, element, attrs) ->
        scope.clickDetailLink = ->
            console.log "loading " + scope.detailLinkHref
            $location.path scope.detailLinkHref

        attrs.$observe 'detailLink', (value) ->
            console.log "set detail link to " + value
            scope.detailLinkHref = value
]

I have a clue what's going on here... my $routeProvider is set up to handle /comments but here I'm trying to append a query string to the route. If I use a regular <a href="#/comments?post={{post.postId}}">, that works fine, but somehow setting the same route via $location.path is not working. This is irrespective of whether this code is in the controller or directive.

jab
  • 4,053
  • 3
  • 33
  • 40

4 Answers4

5

Try scope.$apply? (notice the $)

Satpal
  • 132,252
  • 13
  • 159
  • 168
Brian Lewis
  • 5,739
  • 1
  • 21
  • 28
  • Hmm, yes. That solves that problem, but it still didn't resolve the real issue. Now I have `$apply already in progress`. Wrapping it in a `$timeout` fixes the "already in progress" bit but still doesn't update the path. I'll edit my question.. thanks! – jab Jun 18 '13 at 20:44
  • You might also want to look into $log. – Brian Lewis Jun 18 '13 at 20:56
  • You should be able to do this all in your controller. – Brian Lewis Jun 18 '13 at 21:07
  • I get the exact same problem in my controller -- see edit above. – jab Jun 18 '13 at 21:08
  • from what I can tell, the route does actually change but since it is the same hash it doesn't re-route. It looks like you want to use $location.search(); http://docs.angularjs.org/api/ng.$location#search – Brian Lewis Jun 18 '13 at 21:28
0

The problem is that Angular's $routeProvider doesn't match paths with a query string, like the one I was providing, so it was matching my original page again and reloading it. Similar solution here. It's kind of a strange symptom, though.

Community
  • 1
  • 1
jab
  • 4,053
  • 3
  • 33
  • 40
0

scope.$apply worked for me. Try it first.

Mark Okhman
  • 564
  • 6
  • 13
0

$location.path does not support any param.

Use $location.url instead.

shilovk
  • 11,718
  • 17
  • 75
  • 74