Snackoverflow
Snackoverflow

Reputation: 6271

AngularJS ng-options from nested array

Is it possible to use nested for-loops in an ng-options expression?

The following python-style syntax does not work in AngularJS v1.5.8:

ng-options="user for group in userGroups for user in group.userNames"

angular.module('myApp', [])
       .controller('LoginController', ['$scope', function ($scope) {
  $scope.userGroups = [{
      groupId: 1,
      groupName: 'owner',
      userNames: [
        'John',
        'Mary'
      ]
    },
    {
      groupId: 2,
      groupName: 'admin',
      userNames: [
        'Fred'
      ]
    },
    {
      groupId: 3,
      groupName: 'client',
      userNames: [
        'Company1',
        'Company2',
        'Company3'
      ]
    }
  ];
  $scope.selectedUserName = null;
  $scope.$watch('selectedUserName', function(newValue, oldValue) {
    console.log('selectedUserName changed from', oldValue, 'to', newValue);
  });
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="LoginController">
  <select 
    id="form-login-user" 
    ng-model="selectedUserName" 
    ng-options="user for group in userGroups for user in group.userNames"
  >
    <option></option>
  </select>
</div>

Upvotes: 0

Views: 87

Answers (0)

Related Questions