ng + bootstrap breadcrumbs directive
by sunnycyk
HTML
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css">
<ul id="home" bread-crumbs></ul>
<p>
Above is a bootstrap-styled Breadcrumbs control that is backed by a global breadcrumbs service powered by angular. The id attribute of the <tt><ul></tt> refers to what set of breadcrumbs the service governs. Code can register breadcrumbs using the push() method of the BreadCrumbsService to add entries.
</p>
<form ng-controller='foo'>
<button ng-click='pushSomething()'>Add Breadcrumb</button>
</form>
JavaScript
angular.module('fiddle', ['ngBreadcrumbs']).config( function( $controllerProvider ) {
$controllerProvider.register( 'foo', function( $scope, BreadCrumbsService ) {
$scope.pushSomething = function() {
BreadCrumbsService.push( 'home', {
href: '#/library/data/foo',
label: 'Foo'
} );
};
} );
} ).
run(
function(BreadCrumbsService) {
BreadCrumbsService.push("home",
{
href: '#/',
label: 'Home'
});
BreadCrumbsService.push("home",
{
href: '#/library',
label: 'Library'
});
BreadCrumbsService.push("home",
{
href: '#/library/data',
label: 'Data'
});
});
angular.module('ngBreadcrumbs', []).factory('BreadCrumbsService', function($rootScope, $log) {
var data = {};
var ensureIdIsRegistered = function(id) {
if (angular.isUndefined(data[id])) {
data[id] = [];
}
};
return {
push: function(id, item) {
ensureIdIsRegistered(id);
data[id].push(item);
$log.log( "$broadcast" );
$rootScope.$broadcast( 'breadcrumbsRefresh' );
},
get: function(id) {
ensureIdIsRegistered(id);
return angular.copy(data[id]);
},
setLastIndex: function( id, idx ) {
ensureIdIsRegistered(id);
if ( data[id].length > 1+idx ) {
data[id].splice( 1+idx, data[id].length - idx );
}
}
};
}).directive('breadCrumbs', function($log, BreadCrumbsService) {
return {
restrict: 'A',
template: '<ul class="breadcrumb"><li ng-repeat=\'bc in breadcrumbs\' ng-class="{\'active\': {{$last}} }"><a ng-click="unregisterBreadCrumb( $index )" ng-href="{{bc.href}}">{{bc.label}}</a><span class="divider" ng-show="! $last">|</span></li></ul>',
replace: true,
compile: function(tElement, tAttrs) {
return...