Reputation: 44739
In AngularJS, I can successfully bind text inputs to elements of arrays:
<input type="text" ng-model="foo[2]" />
Is this allowed, or does it just work by accident?
When I try to bind select
elements or checkbox input to array elements they fail to work - i.e. the select
element does not change the displayed, or bound, value on selection and the checkbox does not display a tick when clicked.
Am I missing something here?
Update: It works in JSFiddle: http://jsfiddle.net/azFzc/
Upvotes: 3
Views: 5363
Reputation: 1553
I modified the above example to show non numeric array assignment through binding. Which is most useful when dealing with more complex data or when your array uses a key system for updating and retrieving values.
https://jsfiddle.net/9obtkoa7/
HTML
<div ng-app>
<div ng-controller="MyController">
Select
<select ng-change="changed()"
ng-options="option.value as option.label for option in options" ng-model="ar['SomeId']">
</select>
</div>
</div>
JS
function MyController($scope){
$scope.options = [
{ label : "first element", value : '1' },
{ label : "second element", value : '2' },
]
$scope.ar = [];
$scope.ar['SomeId'] = '1';
$scope.changed = function(){
console.log($scope.ar['SomeId']);
}
}
Upvotes: 1
Reputation: 840
It does work on select elements
Look this jsfiddle http://jsfiddle.net/fStE7/
HTML
<div ng-app>
<div ng-controller="MyController">
Select
<select ng-change="changed()"
ng-options="option.value as option.label for option in options" ng-model="ar[0]">
</select>
</div>
</div>
JS
function MyController($scope){
$scope.options = [
{ label : "first element", value : 0 },
{ label : "second element", value : 1 },
]
$scope.ar = [];
$scope.ar[0] = 0;
$scope.changed = function(){
console.log($scope.ar[0]);
}
}
Upvotes: 2