ng-options examples

by Tarek Faham

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="demoApp">
    <div ng-controller="DemoController">
        <div>
            <h2>Shiny label</h2>
            <select ng-model="shiny"
                ng-options="opt.value as opt.label for opt in options">
            </select>

            The value selected is {{ shiny }}.
        </div>
        <div>
            <h2>Complex object</h2>
            <select ng-model="complex"
                ng-options="opt as opt.label for opt in options track by opt.value">
            </select>

            The value selected is {{ complex }}.
        </div>
        <div>
            <h2>Tarek Example with Array</h2>
            <select ng-model="arrOptSelected"
                ng-options="o as o for o in arrOpt track by o">
            </select>

            The value selected is {{ arrOptSelected }}.
        </div>
    </div>
</body>

JavaScript

angular.module('demoApp', []).controller('DemoController', function($scope) {

  $scope.options = [
    { label: 'one', value: 1 },
    { label: 'two', value: 2 }
  ];
  
  $scope.arrOpt = ["One","Two","Three","Four"];
    
  $scope.shiny = 2;    
  $scope.complex = $scope.options[1];
  $scope.arrOptSelected = "Two";
});