I have implemented Angular UI-Router for state management in my app. It works fine when the user clicks on the various parts of the page and the appropriate information loads in the view. However, when the user refreshes the page from a state other than the initial state the page loads as if it were in the initial state. Here are the details...
This is a catalog of posts and we have the initial view which lists all the posts available. Then we have sections and subsections. If the user clicks for either of these then only the posts with the appropriate categories will be displayed.
Here is the config:
app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('initial', {
url: '/',
templateUrl: 'list_posts.html'
})
.state('category', {
url: '/:category',
templateUrl: 'list_posts.html'
})
.state('subcategory', {
url: '/:category/:subcategory',
templateUrl: 'list_posts.html'
})
.state('singlePost', {
url: '/:category/:subcategory/:post',
templateUrl: 'single_post.html'
});
$urlRouterProvider.when('', '/');
});
And my controller works like this:
I have a variable called
$scope.posts = [];
Then I call a service function in order to populate the array with all the post objects.
Then I set up a listener for a successful state change
$scope.$on('$stateChangeSuccess', function () {
$scope.updatePosts( $stateParams );
});
So effectively, we start at the '/' route and if the user clicks to load a specific section then the url will change and the name of that section will be in $stateParams. Then the listener fires and calls the updatePosts method. This method will empty posts array and reload it with only the posts that have that section name as a category. Once this array is updated then the view changes to reflect the new filtered list of posts.
Here is the updatePosts function
$scope.updatePosts = function ( cats ) {
var length = $scope.dataset.length;
$scope.posts = [];
if ( Object.keys(cats).length == 0 ) {
console.log('empty cats object');
$scope.posts = $scope.dataset;
console.log($scope.posts);
}
else if ( Object.keys(cats).length == 1 ) {
console.log('one category');
console.log(cats);
for (var i = 0; i < length; i++) {
if ( $scope.dataset[i].category_slugs.indexOf( cats.category ) > -1 ) {
$scope.posts.push( $scope.dataset[i] );
}
}
}
else if ( Object.keys(cats).length == 2 ) {
console.log('two categories');
console.log(cats);
for (var i = 0; i < length; i++) {
if ( $scope.dataset[i].category_slugs.indexOf( cats.category ) > -1 && $scope.dataset[i].category_slugs.indexOf( cats.subcategory ) > -1 ) {
$scope.posts.push( $scope.dataset[i] );
}
}
console.log($scope.posts);
}
};
Again, the issue is that this all works just fine until the user decides to refresh the page while it is in a 'category', 'subcategory', or 'singlePost' state. Instead of returning to the appropriate list of filtered posts it will just revert back to the initial state even though the url says otherwise.
Any suggestions on where the problem lies?
Thank you