Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular UI router, how to get a list of ancestors of current state from controller?

My states hierarchy is (from top to bottom):

  1. root
  2. account
  3. account.invoices
  4. 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).

like image 815
gremo Avatar asked Feb 19 '15 13:02

gremo


2 Answers

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.

like image 188
JcT Avatar answered Oct 21 '22 15:10

JcT


In your controller:

function getParentList(state) {
 var parentList = [];
 var state = state.parent;
 while(state) {
  parentList.push(state.toString());
  state = state.parent;
 }
 return parentList;
}

var parents = getParentList($state.$current);
like image 40
Wawy Avatar answered Oct 21 '22 15:10

Wawy