I'm sure this has been answered a thousand times but I can't figure out why I can only redirect using window.location.href
after hours of searching. What's going on?
angular.module(..., [])
.config([..., function(...) {
/* Route Provider and ngRoute reference removed as per comment below */
$stateProvider
.state('login', {
url : '/login',
controller: 'loginCtrl',
templateUrl: '/login'
})
.state('home', {
url: '/',
templateUrl: '/views/index',
controller: 'HomeCtrl'
});
$locationProvider.html5Mode(true);
}
])
.run(['$state', '$rootScope', function ($state, $rootScope) {
$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams) {
if ($rootScope.username == null || $rootScope.password == null) {
if (toState.templateUrl == "/login") {
} else {
event.preventDefault();
$state.go("login");
}
}
});
}
]);
Update: StateChangeStart is being called twice, the second time with the login state. There are no errors thrown in the console. I'm very new to angular, so I'm open to any suggestions if I'm doing something drastically wrong. If you need any additional code (ex: controller, service) let me know and I'll post it.
However, on displaying the welcome page, even though username and password are null, it stays on the welcome page. Entering /login
in the browser works as expected.
As per Angular $location.path not working:
/* snip */ else {
$rootScope.$apply(function () {
$location.path('login');
});
} /* snip */
gives me an error: $digest already in progress
.
Further details:
I just found out that if I remove the $locationProvider.html5Mode(true);
line,
stateChangeStart is not called when I load the page.
Server is ASP.Net.
Edit 2 It looks like angular is actually getting the login page, but doesn't know where to put it?