3

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/

2 Answers 2

2

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]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it was a bug in my app, not in my understanding of AngularJS.
1

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']);
    }
}

Comments

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.