Search code examples
angularjsangular-ngmodelng-optionsangularjs-ng-options

AngulaJS ng-options initially selected value from an


I have an object with property: value structure with should be used for the ng-options to create the select dropdown. I also have a ng-model variable which contains the property which should be currently selected. The problem is that I can't figure out how to fix the initial selection. You can find the code here

<select ng-model="selectedCar" ng-options="id as value for (id, value) in cars track by id">

http://jsbin.com/wukanenozu/1/edit?html,js,output


Solution

  • Do not use "track by"

    Do not use as and track by in the same expression. They are not designed to work together.

    <select ng-model="selectedCar" ng-options="id as value for (id, value) in cars ">
    </select>
    

    DEMO

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.cars = {
            frd : "Ford",
            ft1 : "Fiat",
            vlv : "Volvo"
        }
        $scope.selectedCar = 'ft1';
    });
    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="myCtrl">
    
    <p>Select a car:</p>
    
    <select ng-model="selectedCar" ng-options="id as value for (id, value) in cars ">
    </select>
    <h1>You selected model: {{selectedCar}}</h1>
    
    </div>
    
    <p>This example demonstrates the use of an object as the data source when creating a dropdown list.</p>
    
    
    
    </body>
    </html>