anuloo
anuloo

Reputation: 15

angular ui-router $stateProvider states iterate through object properties

I have been trying to dynamically populate the navbar from my states configured in $stateProvider. when i try to get the state name or the url or any other properties I get undefined, I have been using the $state.get() but I could not find any example where kind of explain it how to use to iterate through states

Just for clarity and an example lets use the bellow states, I need to be able to dynamically generate the navbar with the states name (main, home, about)

$stateProvider
  .state('main', {
    abstract: true,
    templateUrl: 'app/states/main/main.html'
  })
  .state('home', {
    url: '/',
    templateUrl: 'app/states/main/home/home.html',
    controller: 'HomeController',
    controllerAs: 'home'
  })
  .state('about', {
    url: '/about',
    templateUrl: 'app/states/main/about/about.html',
    controller: 'AboutController',
    controllerAs: 'about'
  })

see the implementation of the controller its probably nonesense

angular
.module('myapp')
.controller('NavBarController', NavBarController); 
function NavBarController($scope, $state) {
   var states = $state.get();
    angular.forEach(states, function (value, key) {
        // value returns [Object Object];
        // key returns numbers from 0 to 3
        console.log('get states ----   ')
    });
}

Upvotes: 0

Views: 753

Answers (2)

willie17
willie17

Reputation: 901

$state.get() return an array while for ... in iterates over properties in object.

You should use angular.forEach instead:

// Get all state config objects
var states = $state.get();

// Loops through each state in states
// "value" is each state config object
angular.forEach(states, function(value, key) {
  // Log each state name
  console.log(value.name);
});

Upvotes: 0

Jagrut
Jagrut

Reputation: 922

Did you try, console.log(state.name) to get the names of each state and accordingly other stuffs?

Upvotes: 0

Related Questions