Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare URL in Angular using $location.path()

Hi I am trying to make certain sections open (i.e. 'call.html' not to perform authentication) for my single page app in angular.js using login service.

I would like to know how can I get path(http://www.example.com/app/#/call/1234) so I can compare it and redirect to 'login' page if the page is not 'call.html' ?

I have got the following code in my app.js which seems to work but doesn't work in Chrome and I get following error:

TypeError: $location.path(...).contains is not a function

my app.js.

app.run(['$rootScope', '$location', '$cookieStore', '$http',
    function ($rootScope, $location, $cookieStore, $http)
    {
        $rootScope.globals = $cookieStore.get('globals') || {};
        if ($rootScope.globals.currentUser)
        {
            $http.defaults.headers.common['Authorization'] = 'Basic' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
        }
        $rootScope.$on('$locationChangeStart', function (event, next, current)
        {
            // redirect to login page if not logged in
            if($location.path().contains('call'))
            {
                return;
            }

            else
            {
                if ($location.path() !== '/login'  && !$rootScope.globals.currentUser && $location.path() !=='/')
                {
                    $location.path('/login');
                }
            }
        });
    }
]);

Any help of how to address this would be greatly appreciated.

like image 483
snowflakes74 Avatar asked Aug 30 '26 21:08

snowflakes74


2 Answers

contains is a jquery method not of angularjs. So, using this line of code:

if($location.path().contains('call')){

will obviously throws an error, "contains is not a function".

You can use indexOf:

if($location.path().indexOf('call') > -1){
like image 112
Bhojendra Rauniyar Avatar answered Sep 01 '26 15:09

Bhojendra Rauniyar


The $locationProvider uses hashbangs by default (as evident from your path /app/#/call/1234) so if you don't set html5Mode to true, you will get an empty string if you try to fetch the URL path.

Try setting $locationProvider.html5Mode(true) and you should be able to get the URL path.

like image 45
Jia Jian Goi Avatar answered Sep 01 '26 15:09

Jia Jian Goi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!