nickponline
nickponline

Reputation: 25914

How do I prevent AngularJS binding recursively?

I have a select:

<select ng-model="p.value" ng-options="q for q in p.value">
<option value="">Select an animation</option>
</select> 

Where p.value is ['AAAAA', 'BBBBB', 'CCCCC'] but when I select an option the select updates and shows a new bunch of options like:

<option>A</option>
<option>A</option>
<option>A</option>
<option>A</option>
<option>A</option>

I've obviously structured things wrong by using the same value in model and options. What is the correct way to do things?

Upvotes: 5

Views: 277

Answers (1)

Mark Coleman
Mark Coleman

Reputation: 40863

You need to separate the array of items and the model

<div ng-app ng-controller="MyCtrl">
    <select ng-model="p.selected" ng-options="q for q in p.value">
        <option value="">Select an animation</option>
    </select>
    {{p.selected}}
</div>


function MyCtrl($scope) {

    $scope.p = {
        value: ['AAAAA', 'BBBBB', 'CCCCC'],
        selected : null
    };
}

What is happening in your example is as soon as you select AAAAA p.value now references a list of characters and since ng-options is bound to the same $scope property the drop down list updates and produces your result you are seeing.

Example on jsfiddle

Upvotes: 4

Related Questions