Search code examples
angularjsng-options

How can i get this ng-option to init with selected object value?


I´m trying to start this select with a predefined option selected. But i need to use as value an object like you can see in my code. I need to get an id in data.selected.

index.html

<div ng-controller="MyCtrl">{{data|json}}
        <select ng-model="data.selected" 
            ng-options="p.id.another group by p.id.proxyType for p in proxyOptions" >
        </select>
</div>

app.js

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.proxyOptions = [{
        id: { proxyType: 'None', another: 1 }
    }, {
        id: { proxyType: 'Manual', another: 2 }
    }, {
        id: { proxyType: 'Automatic', another: 3 }
    }];

    $scope.data = {};
    $scope.data.selected = $scope.proxyOptions[0].id; }

Fiddle

http://jsfiddle.net/fh01qndt/2/

New Fiddle based on Darren comments

http://jsfiddle.net/fh01qndt/5/

It works but i still need to specify the selected options this way:

    $scope.data.selected = {proxyType: 'Manual', another: 2};

Solution

  • Use $scope.data.selected = $scope.proxyOptions[0] instead. Your way is creating another object which is different from your proxy options.

    You just changed your questions code...Please don't do that.

    Remove the .id from your assignment - ng-model will be the entire option object not just the Id

    Here is your exact fiddle, but with the .id removed from your assignment. JSFiddle

    UPDATE

    Ok, So having looked again at your code I have tried to understand what you're trying to achieve - i also noticed that I misread your original JSON object regarding the id - sorry; i saw id and assumed it referred to "an id" and not an object..

    However, I think what you're trying to do is set your selected option in code, so you would need to search through the list and find your match, no?

    If that's the case, then this fiddle shows ng-init() calling a function to do just that.

    Any good to you? Another Fiddle, using ng-init