Angular UI router, how to get a list of ancestors of current state from controller?
angular-ui, angular-ui-router, angularjs
Solution
Have a look at `$state.$current.includes`; it appears to return an object with keys matching the current and parent states. I believe these are all states that would pass a `$state.includes()` test.
Problem
My states hierarchy is (from top to bottom): - `root` - `account` - `account.invoices` - `account.invoices.detail` When I'm in `account.invoices.detail` state I'd like to get a list of ancestors states: ``` angular .module('app') .controller('InvoiceDetailCtrl', ['$scope', '$state', function ($scope, $state) { var current = $state.current.name; // Get ancestors from current state // Tried $state.current.parent, $state.parent, $state.parent(current) }]); ``` Angular UI router allows you to get transition to parent state (i.e. from a view with `data-ui-sref="^"`), so it should be possible to achieve this (follow up the chain of ancestors up to `root`). I need this to build a auto-breadcrumbs-like functionality. EDIT: ended up with this, thanks to the accepted answer: ``` var current = $scope.$state.$current, parent = current.parent, ancestors = [current.name]; while (typeof parent != 'undefined' && parent.name.length) { ancestors.push(parent.name); parent = parent.parent; } ``` If you ask why the check for `parent.name.length` its because there is something like a "root" state in Angular UI (can't get any documentation about).