Reputation: 3427
I have a below code snippet
HTML
<div ng-controller="MyCtrl">
<div ng-if="quan!=true">
<select ng-model="selectedItems" ng-init="selectedItems = selectedItems + ''">
<option ng-repeat="value in arr | limitTo:quantity">{{value}}</option>
</select>
</div>
<div>
<a href="#" ng-click="submit()">Submit</a>
</div>
</div>
JS
$scope.arr = [];
$scope.quan=false;
for(var a=1; a<=10; a++) {
$scope.arr.push(a);
}
$scope.selectedItems = $scope.arr[0];
$scope.quantity = 10; //just hardcoded
Here, when I click submit button, I didn't get the value whatever I have selected in the dropdown. I was getting undefined for selectedItems.
And also first option needs to be selected in the select box.
I think I'm missing something!
Upvotes: 1
Views: 2495
Reputation: 3822
After changing to $scope.selectedItems = $scope.arr[0];
, you need to initialize your option value ng-init="selectedItems = selectedItems + ''"
because angular use strict comparison.
See this working fiddle.
also you don't need to pass selected item in click event, submit(selectedItems)
. because it is already in controller scope.
Also I would recommend changing your options structure to avoid ng-init
.
Something like :
options = [{
name: 'key1',
value: 'value1'
}, {
name: 'key2',
value: 'value2'
}];
Upvotes: 2
Reputation: 837
HTML:
<select ng-model="selectedItem" >
<option ng-repeat="value in arr | limitTo:quantity">{{value}}</option>
</select>
<div>
<a href="#" ng-click="submit();">Submit</a>
</div>
JS:
$scope.arr = [];
for(var a=1; a<=10; a++) {
$scope.arr.push(a);
}
$scope.selectedItem = $scope.arr[0];
$scope.quantity = 10; //just hardcoded
$scope.submit = function(){
console.log($scope.selectedItem); // you will get the selected value here, if you want it after button click.
};
Because of angular's 2 way binding, it would be available as soon as you select something. You do not have to pass it as function parameter from HTML
Upvotes: 0