简体   繁体   中英

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 ----   ')
    });
}

您是否尝试使用console.log(state.name)来获取每个州的名称以及相应的其他内容?

$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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM