0

I am trying to push an array of values inside select box using ng-options in Angularjs.

Handlebars:

<div class="col-md-8">
    <select ng-options="item as item.label for item in items track by 
    item.id" ng-model="selected">
        <option></option>
    </select>
</div>

Controller:

var app = angular.module('myapp', []);

app.controller('mycontroller', function($scope) {

$scope.arealistArray=[];
$scope.items=[]; 

for(j=1;j<3;j++){
    $scope.arealistArray.push([{id: 'id'+j,label: 'aLabel'+j,subItem: { 
    name: 'aSubItem'+j }}]);
} 

$scope.items = $scope.arealistArray;

My options are appending in the select box, but the value and label are undefined for appended options. Is there any restriction using push in ng-options? Or any thing I want to change here?

2 Answers 2

1

You are pushing an array in an other array. You shall remove the "[]".

$scope.arealistArray.push({
  id: 'id' + j,
  label: 'aLabel' + j,
  subItem: {
    name: 'aSubItem' + j
  }
});

Here's a working fiddle based on your code.

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome. Notice that I've updated my answer. After some research the track by expression you have on your code is right.
1
$scope.arealistArray.push([{id: 'id'+j,label: 'aLabel'+j,subItem: { 
name: 'aSubItem'+j }}]);

if it's like above you need to specify index or else

 ng-options="item as item.label for item in items[0] track by item.id"

if its an object remove the [] while doing push.

$scope.arealistArray.push({id: 'id'+j,label: 'aLabel'+j,subItem: { 
name: 'aSubItem'+j }});

var app = angular.module('myapp', []);

app.controller('mycontroller', function($scope) {

$scope.arealistArray=[];
$scope.items=[]; 

for(j=1;j<3;j++){
    $scope.arealistArray.push({id: 'id'+j,label: 'aLabel'+j,subItem: { 
    name: 'aSubItem'+j }});
} 

$scope.items = $scope.arealistArray;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycontroller" class="col-md-8">
    <select  ng-options="item as item.label for item in items track by 
item.id" ng-model="selected">
        <option></option>
    </select>
</div>

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.