Search code examples
angularjsselectng-optionsangularjs-ng-options

AngularJS not populating or inititializing select


In the AngularJS doc's, they reference this fiddle from which I've derivded a simple jsfiddle here.

The entire HTML:

<body ng-app="demoApp">
<div ng-controller="demoController">
<table>
  <tr>
    <td>Select Category
      <select ng-model="selectedCategory"
              ng-options="cat as cat for cat in categories">
      </select>
    </td>
    The category selected is: {{selectedCategory}}
  </tr>
  <tr>
    <td>Select CategoryId
      <select ng-model="selectedCatId"
              ng-options="ds as ds.id for ds in dataset">
      </select>
      The category id selected is: {{selectedCatId}}
    </td>
  </tr>
</table>
</div>
</body>

The AngularJS controller:

angular.module('demoApp', []).controller('demoController', function($scope) {
  $scope.categories = ["CAT1", "CAT2", "CAT3"];
  $scope.dataset = [
                    { "category": "CAT1", "id": "CAT_ID11" },
                    { "category": "CAT1", "id": "CAT_ID12" }
                   ];

  $scope.selectedCategory = categories[1];
  $scope.selectedCatId = $scope.dataset[1];
});

The result I'm seeing in the fiddle:

enter image description here

Besides not seeing the initialization, I'm not seeing the list items either and am not sure why. What am I missing?


Solution

  • categories was not defined. Golbal declaration-

    var categories=["CAT1", "CAT2", "CAT3"];
    

    Also categories is an array, So,

    <select ng-model="selectedCategory"
                    ng-options="cat for cat in categories">
            </select>
    

    Check this fiddle-

    http://jsfiddle.net/RahulB007/0a1xbxm2/2/