1

I'm trying to programmatically update the selected item from my controller and it's not working. When I click the submit button, all it does is clear out the select. What I expect is that the second option (Perth) gets selected.

Look at this plunker for more info. http://jsfiddle.net/ky5F4/

Thanks

<div ng-controller="MyController" ng-app>
    <div>Number of datasets= {{datasets.length}}</div>
    <div>
        <select class="dataset" size="1" ng-model="selectedDataset">
            <option ng:repeat="dataset in datasets" value="{{dataset.name}}">
                <h3>{{dataset.name}}</h3>
            </option>
    </div>
    <input type="button" value="submit" ng-click="Select()"></input>
</div>

function MyController($scope) {
    $scope.datasets = [{
        id: 'id-1',
        name: 'Brisbane'
    }, {
        id: 'id-2',
        name: 'Perth'
    }, {
        id: 'id-3',
        name: 'Melbourne'
    }];

    $scope.selectedDataset = 'id-1';

    $scope.Select = function () {
        alert('testing');
        $scope.selectedDataset = 'id-2';
    }
}
2
  • I see you have ng:repeat instead of ng-repeat...not that this will help the issue Commented Jan 10, 2014 at 17:31
  • yeah I realized, copied someone else's fiddle. Commented Jan 10, 2014 at 17:32

1 Answer 1

13

Use ng-options instead of ng-repeat.

<select class="dataset" size="1" ng-model="selectedDataset" 
    ng-options="dataset.id as dataset.name for dataset in datasets">

Working fiddle

You can see the docs here

Sign up to request clarification or add additional context in comments.

2 Comments

Funny that the fix is so subtle... Thanks! I will mark as correct when the time limit is over.
I had a similar problem where my selectbox just goes blank when I change the model via another model-bound input: <select ng-model="item[key]" ng-options="option.ID as option.Name for option in item.Options"></select> -- I thought it was due to the indexed model, but it seems to work fine as simple version and complex v1 and complex v2. Just sharing :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.