sukesh
sukesh

Reputation: 2423

How to use ng-options in angularjs

The select element is not bound as expected.

html:

<select ng-model="SelectedPage" 
 ng-change="ShowPageResult();" ng-options="o for o in PageNumbers">
</select>

ctrl.js:

function BindPageNumbers() {        
        $scope.PageNumbers = [];
        for (var i = 1; i <= 2) ; i++) {
            $scope.PageNumbers.push(i);
        }      
    }

output:

<option value="0"label="1">1</option>
<option value="1" label="2">2</option>

if i put $scope.PageNumbers.push(i.toString());, then the output is

<option value="?"label=""></option>
<option value="0" label="1">1</option>
<option value="1" label="2">2</option>

expected:

<option value="1">1</option>
<option value="2">2</option>

what should be done to get the desired o/p : http://jsfiddle.net/s222904f/

Upvotes: 1

Views: 67

Answers (2)

KreepN
KreepN

Reputation: 8598

Check it: http://jsfiddle.net/khwuv4Lj/

Per the answer here, the empty option exists because the

ng-model="SelectedPage"

line binds it to an empty string. You can avoid this by setting the default value if the select in the scope.

Edit: Plnkr was updated to fix the OP's comment.

enter image description here

Upvotes: 0

von v.
von v.

Reputation: 17108

In your controller:

$scope.PageNumbers = [];
for (var i = 1; i <= 2 ; i++) {
    $scope.PageNumbers.push({ id: i, value: i });
}

In your view:

<select ng-model="SelectedPage"    
    ng-options="o.id for o in PageNumbers track by o.value"></select>

Upvotes: 2

Related Questions