Skip to content

Instantly share code, notes, and snippets.

@zachsnow
Last active January 1, 2016 06:09
Show Gist options
  • Save zachsnow/8102949 to your computer and use it in GitHub Desktop.
Save zachsnow/8102949 to your computer and use it in GitHub Desktop.
ngAutoTitle

ngAutoTitle

A collection of directives for managing the <title /> of an AngularJS application.

Usage

  1. Mark the element that you'd like to use as your title with the ng-auto-title directive; usually this will be <title />.

    <title ng-auto-title></title>
  2. For any element that should change the title when it is rendered, define the title with the ng-title directive.

    ...
(function(){
app.directive('ngAutoTitle', [
'$document',
'autoTitle',
function($document, autoTitle){
return {
link: function(scope, element, attrs){
var unlisten = autoTitle.listen(function(newTitle){
$document.title = newTitle;
});
scope.$on('$destroy', function(){
unlisten();
});
}
};
}
]);
app.directive('ngTitle', [
'autoTitle',
function(autoTitle){
return {
link: function(scope, element, attrs){
var title = autoTitle.create();
attrs.$observe('ngTitle', function(newTitle){
autoTitle.update(title, newTitle);
});
scope.$on('$destroy', function(){
autoTitle.destroy(title);
});
}
};
}
]);
})();
(function(){
app.factory('autoTitle', [
function(){
var listeners = [];
var titles = [];
var notify = function(){
var value = '';
if(titles.length){
value = titles[titles.length - 1].value;
}
_.forEach(listeners, function(listener){
listener(value);
});
};
var service = {
listen: function(fn){
listeners.push(fn);
return function(){
_.ref.remove(listeners, fn);
};
},
create: function(value){
var newTitle = {
value: ''
};
titles.push(newTitle);
service.update(newTitle, value);
return newTitle;
},
update: function(title, value){
title.value = value || '';
notify();
},
destroy: function(title){
_.ref.remove(titles, title);
notify();
}
};
return service;
}
]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment