AngularJS Example
HTML
<div ng-app="">
<div ng-controller="MyCntrl">
<button ng-click="setSelectedWorks()">Step 1. Set selected works</button>
<button ng-click="clearSelected()">Step 2. Clear Selected</button>
<button ng-click="setSelectedDoesNot()">Step 3. Set selected does not</button>
<button ng-click="setSelectedDoesButNotOptimal()">Step 4. Set selected does work but what about big lists?</button>
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</div>
CSS
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<script src="http://docs.angularjs.org/angular-1.0.1.min.js"></script>
<style>
.ng-invalid { border: 1px solid red; }
JavaScript
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.setSelectedWorks = function() {
alert("1");
$scope.color = $scope.colors[2]; // red
console.log('setSelectedWorks',$scope.colors, $scope.colors[2], $scope.color);
};
$scope.setSelectedDoesNot = function() {
$scope.color = {name:'red', shade:'dark'};
console.log('setSelectedWorks',$scope.colors, $scope.colors[2], $scope.color);
};
$scope.setSelectedDoesButNotOptimal = function() {
angular.forEach($scope.colors, function(val,i) {
if(val.name == $scope.colors[2].name) {
$scope.color = val;
}
});
};
$scope.clearSelected = function() {
$scope.color = null;
};
}