I've been learning Angular for the past couple of weeks and I've just implemented the breadcrumbs service but it's not working when I refresh the page, or when I first navigate to the page the breadcrumbs exist on. If I return to the home page and then back to the about page, the crumbs work as intended.
Please see this live example of its current state.
I believe it could be the way I'm including the crumbs and that I'm unaware of the rules behind such activities.
The about page has a ng-include
which grabs the template for the crumbs:
<ul id="breadcrumb" ng-controller="crumbCtrl">
<li><a href="#" title="Home">Home</a></li>
<li ng-repeat="breadcrumb in breadcrumbs.getAll()">
<ng-switch on="$last">
<span ng-switch-when="true">{{breadcrumb.name}}</span>
<span ng-switch-default><a href="{{breadcrumb.path}}">{{breadcrumb.name}}</a></span>
</ng-switch>
</li>
</ul>
I do not wish to display the crumbs on the home page for obvious reasons, which is why I have included it only on the about page.
Could someone enlighten me as to a way I should either hide it on the home page only or a correct method of deployment please.
Also, here is my main app.js:
var app = angular.module('dunnApp', ['ngRoute', 'services.breadcrumbs']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// Home
.when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
// Pages
.when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
// else 404
.otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);
angular.module('dunnApp').controller('crumbCtrl', ['$scope', '$location', '$route', 'breadcrumbs',
function ($scope, $location, $route, breadcrumbs) {
$scope.location = $location;
$scope.breadcrumbs = breadcrumbs;
console.log("Crumbs online.");
}]);
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
console.log("Page Controller online.");
});
Here is what happens in your code:
breadcrumbs
service is not initialized until crumbCtrl
gets initializedcrumbCtrl
gets into action when breadcrumbs
template is included to About page.breadcrumbs
service you listen for $routeChangeSuccess
events, but this "listener" gets active once the breadcrumbs
service is initialized, which happens after you navigate to About page once.So I would suggest you, to place the $rootScope.$on('$routeChangeSuccess', ... )
on a place where it will run from the application's startup (eg. in app.run(function($rootScope)) { ... }
), and add to breadcrumb
service a setBreadcrumbs()
function which will be called inside the $routeChangeSuccess
listener (breadcrumbs.setBreadcrumbs(result)
).
Here is a working version of what I'm suggesting.