4

I am generating some <option> elements using the ng-repeat directory. Using ng-repeat instead of ng-options is intentional.

However, it generates an empty option in addition to the actual array. Here's the code:

<select name="type" class="form-control" ng-model="selected_type" ng-change="select_change()" >
    <option ng-repeat="type in types" value="{{type.value}}">{{type.name}}</option>
</select>

$scope.types = [
    {value: '1', name: 'Sale'}, 
    {value: '2', name: 'Other'}
];
$scope.selected_type = $scope.types[0].value;

And a fiddle: http://jsfiddle.net/HB7LU/521/

3
  • Why is ng-options not appropriate for what you intend to achieve? Commented Sep 26, 2013 at 10:03
  • Removing ng-model from select fixed the issue - jsfiddle.net/HB7LU/529 Commented Sep 26, 2013 at 10:06
  • thsi actually worked jsfiddle.net/aBPdv Commented Sep 26, 2013 at 10:08

3 Answers 3

1

Here's a working fiddle, using ng-options

http://jsfiddle.net/HB7LU/527/

<select ng-model="selected_type" ng-change="select_change()" ng-options="c.name for c in types">

Then on script.js:

$scope.selected_type = $scope.types[0];

With that said, since you're just partly using angularjs you can just map the data in an array before you actually post in say in PHP.

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

Comments

1

try ng-options instead of making options tag yourself:

<div ng-controller="MyCtrl">
    <select ng-model="selected_type" ng-change="select_change()" ng-options="type.value as type.name for type in types">
    </select>
</div>

http://jsfiddle.net/aBPdv/

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

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.types = [
    {value: '1', name: 'Sale'}, 
    {value: '2', name: 'Other'}
    ];
    $scope.selected_type = $scope.types[0].value;
    $scope.select_change = function(x){
        alert($scope.selected_type);
    }
}

Comments

1

Just use the ng-model attributes on your option tag not on your select tag (use it where the ng-repeat is defined) like that :

<select ng-change="select_change()">
    <option ng-model="selected_type" ng-repeat="type in types" value="{{type.value}}">{{type.name}}</option>
</select>

Then change your

$scope.selected_type = $scope.types[0].value;

to

$scope.selected_type = $scope.types;

But your ng-change will not work because no ng-model attribute is set so no ngModelController is assign to this element.

So if you want to know when the value of the select change you have to do a directive on the select element.

For all these reasons ng-options is always and i say always the right direction for a select input usage.

1 Comment

This is in the right direction. But by doing this, I can't detect what option is chosen

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.