Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate over values in a list in a dictionary for a key angularjs

Tags:

angularjs

I a dictionary with a string key and string list value:

[key1 : value1, value2, value3]
[key2 : value1]
[key3 : value1, value2]

I need to display it in a navbar in angular js.

The angularjs view is :

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" ng-controller="NavCntrl">
    <ul class="nav navbar-nav" ng-repeat="(key, val) in categories">
        <li class="dropdown">
            <a href="#">{{key}}</a>
            <ul class="dropdown-menu">
                <li>
                    <a href="#">{{val}} </a>
                </li>
            </ul>
        </li>
    </ul>
</div>

I am able to display the key however the value for each key is showing as "['value1',value2]"

I tried it like this also:

<li class="dropdown">
            <a href="#">{{key}}</a>
            <ul class="dropdown-menu" ng-repeat="value in key" >
                <li>
                    <a href="#">{{value}} </a>
                </li>
            </ul>
        </li>

However, its showing some garbage values and is not working.

Please help!

like image 391
abhijitsinha89 Avatar asked Nov 28 '25 06:11

abhijitsinha89


2 Answers

After categories is set, its values need to be converted to arrays. Strings have a split method which makes this easy.

$scope.categories={
    key1: 'value1, value2, value3',
    key2: 'value1',
    key3: 'value1, value2'
};
Object.keys($scope.categories).forEach(function(key){
    $scope.categories[key]=$scope.categories[key].split(',');
});
console.log('modified categories',$scope.categories);
like image 93
Remento Avatar answered Nov 29 '25 22:11

Remento


For data

{
    'key1' : ['value1', 'value2', 'value3'],
    'key2' : ['value1'],
    'key3' : ['value1', 'value2']
}

The view should be

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" ng-controller="NavCntrl">
    <ul class="nav navbar-nav" ng-repeat="(key, val) in categories">
        <li class="dropdown">
            <a href="#">{{key}}</a>
            <ul class="dropdown-menu">
                <li ng-repeat="subval in val">
                    <a href="#">{{subval}} </a>
                </li>
            </ul>
        </li>
    </ul>
</div>
like image 27
Gaurav Avatar answered Nov 29 '25 23:11

Gaurav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!