I am having the hardest time getting two way binding to work for SELECT elements. I am trying to change the selected element programmably. I've found several Stackoverflow examples for binding the change event for SELECT, but I've not been many going the other way, where your application code changes the selected element.
There have been a few that I've found that use ng-repeat on an OPTION element but I've a) not been able to get it to work, and b) does not seem to be the "Angular Way".
HTML Code:
<div ng-controller="SIController">
<select id="current-command" ng-model="currentCommand"
ng-options="c as c.label for c in availableCommands track by c.id"></select>
<button ng-click="changeSelectedOption()">Select "open"</button>
Controller Code:
var myApp = angular.module('myApp', []);
function SIController($scope) {
$scope.availableCommands = [
{id: 'edit', label: 'Edit'},
{id: 'open', label: 'Open'},
{id: 'close', label: 'Close'}
];
$scope.currentCommand = "close";
$scope.changeSelectedOption = function() {
$scope.currentCommand = 'open';
};
};
I can verify that $scope.currentCommand is changing when the button is clicked, but the OPTION does not seem to be getting selected.
Is there the working fiddle : http://jsfiddle.net/bzhkkw18/9/
To explain what I've done, there is the name of the function which didn't match on the ng-click
and in the controller.
And the main part was the definition of your option. In your ng-options
you set the all object. If it's what you really want, you have to do the same in your currentCommand
like this :
//Object 2 is close
$scope.currentCommand = $scope.availableCommands[2];