0

I have created one Nav Controller in Angular JS as mentioned below.

weatherApp.controller('navCtrl', ["$scope", "$localStorage", function($scope, $localStorage){

    if($localStorage.user_email){
        var navItems = new Array();
        navItems["/"] = 'Home';
        navItems["/logout"] = 'Logout';
        $scope.navItems = navItems;
    }
    else{
        var navItems = new Array();
        navItems["/"] = 'Home';
        navItems["/login"] = 'Login';
        $scope.navItems = navItems;
    }
    $scope.test = "test";
}]);

I am calling this controller in index.html as shown below.

<ul class="nav navbar-nav" ng-controller="navCtrl">
    <li ng-repeat="(url, navItem) in navItems">
        <a href="#{{ url }}">{{ navItem }}</a>
    </li>
</ul>

if I keep navItems indexes alphanumeric then it does not load values but if I keep its indexes numeric, it show menu items.

Is there any way by which I can use alphanumeric indexes in ng-repeat?

2 Answers 2

1

I think you need a diferent data structure. Something like this:

https://jsfiddle.net/relferreira/3aexpfk5/

JS:

angular.module('app', []);

angular.module('app')
    .controller('MainController', mainController);

mainController.$inject = ['$scope'];

function mainController($scope){

    var vm = this;

  vm.navItems= [
    { path: '/', name: 'Home'},
    { path: '/login', name: 'Login'},
  ];

}

HTML:

<div data-ng-app="app">

  <div data-ng-controller="MainController as mainVm">

    <ul class="nav navbar-nav">
        <li ng-repeat="navItem in mainVm.navItems">
            <a href="#{{ navItem.path }}">{{ navItem.name }}</a>
        </li>
    </ul>
  </div>

</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Your syntax for ng-repeat is correct.

However, do not use Array. Initialize your objects as:

var navItems = {};

As a side note, keeping user email in LocalStorage sounds like a very unusual thing (if this is a client-server app), but of course this ultimately depends on your use case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.