AdtG AdtG - 4 months ago 18
AngularJS Question

ng-options and array from controller

I am new to angular js. I want to show list from controller in drop down. The array is controller variable as defined below:



(function(angular) {
'use strict';
angular.module('staticSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
self = this;
self.options = [
{id: 1, label: "Item 1"},
{id: 2, label: "Item 2"},
{id: 3, label: "Item 3"}
];

$scope.data = {
singleSelect: null,
multipleSelect: [],
option1: 'option-1',
};

$scope.forceUnknownOption = function() {
$scope.data.singleSelect = 'nonsense';
};
}]);
})(window.angular);





Now, I want to show this options array in drop down. The script is as below:



<body ng-app="staticSelect">
<div ng-controller="ExampleController as ctrl">
<form name="myForm">
<label for="singleSelect"> Single select: </label><br>
<select name="singleSelect" ng-model="data.singleSelect" ng-options="ctrl.option.id as ctrl.option.label for ctrl.option in ctrl.options">
</select><br>
<tt>selected = {{data.singleSelect}}</tt><br/>
</form>
</div>
</body>





If options array is in $scope then this works fine. What am I doing wrong here while using controller variable?

Answer

Here is how your ng-options attribute should looks like:

ng-options="option.id as option.label for option in ctrl.options"