user3197307 user3197307 - 2 months ago 10
AngularJS Question

AngularJs path not changing, even after apply

I have a quick question about the chaning of a route trough a custom directive. I set up a menubar diretive and set up a link function. Everything in this function works correctly, but the chaning of the URL trough the

$location.path
does not. Even after using
$rootScope.apply
, it does not change.

define([
'../module',
'../namespace'
],
function (module, namespace) {
module.directive(namespace + '.menubarDirective', function ($location, $rootScope) {
return {
restrict: 'EA',
replace: 'true',
templateUrl: 'scripts/app/menubar/views/menubar.html',
scope: {},
controller: function () {
},
link: function (scope, element, attrs) {

$("#menubarStoreButton").click(function () {
$('.active').removeClass('active');
$(this).addClass('active');
$location.path('/store');
$rootScope.$apply();
})

}
}
});
});


To be clear, I use
requirejs
and $location and
$rootScope
are defined. The weird thing is,
$location.path()
before the replace gives a empty path. Also, the placement of the class 'active' works as intended.

Thanks.

Answer

try using $timeout -

$("#menubarStoreButton").click(function() {
    $('.active').removeClass('active');
    $(this).addClass('active');
    $timeout(function() {
        $location.path('/store');
    });
})