0

Say I have a button that's within the ng-app scope, but outside the ng-controller/ng-view scope.

<html ng-app="myApp">
<!-- ... -->
<body>
    <button id="myButton">Click me!</button>
    <div ng-view> <!-- angular-view --> </div>
</body>
</html>

And I want to change the URL/Route when I click the button.

var button = document.getElementById('myButton');

button.addEventListener('click', function() {
    //code that changes path.
});

How do I do that? If I try window.location.href = '/'; the whole page gets reloaded, not just the view. $location isn't visible from html javascript, so that's not an option neitehr.

If anyone knows a way I can change the path/route/url from javascript, I'd be more than happy to accept any valid answer, or a redirect to some helpful documentary post, or a rederect to another SO question, because I'm trying to find an answer to this for a while and I've got nothing...

I'll note that I tried making a global scope function, but that didn't work, neither.

angular.module('myApp', [])
    .config( ... )
    .run(function($rootScope, $location) {
        $rootScope.setUrl = function(url) {
            $location.path(url);
        };
    })
    .controller(
        .....

and called with setUrl('/');, $root.setUrl('/'); and $rootScope.setUrl('/');, but still nothing ('undefined').

note: the button script is just an example, the real purpose why I'm asking this is a little bit larger, so I'm trying to simplify.

6
  • it should work with $rootScope Commented Dec 19, 2015 at 13:13
  • this might help jsfiddle.net/austinnoronha/nukRe/light Commented Dec 19, 2015 at 13:24
  • @jonasnas unfortunately, doesn't. it returns it as 'undefined function'. Commented Dec 19, 2015 at 13:35
  • are you calling it like this: ng-click="setUrl('/somePath')" ? Commented Dec 19, 2015 at 13:37
  • did, but still didn't work properly. while it doesn't crash, nor report bugs, it still doesn't actually change the location path. Commented Dec 19, 2015 at 13:49

1 Answer 1

2

If your purpose is to change route from outside of the Angular app, then you need to change location hash part:

window.location.hash = 'new-route';

Inside Angular controller use $location.path method.

Sign up to request clarification or add additional context in comments.

1 Comment

only problem with this is, they don't want the hash to be implemented in the URL, so I have set up $locationProvider.html5Mode({ enabled: true, requireBase: false });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.