Reputation: 93
I have a select control in my ionic - cordova app. Each option in select control has value and text which is loading with ng-repeat. When I set the ng-model initially the selection not changing. Please help me how to fix this. Below is the code I used;
<select ng-model="myselecteditem">
<option ng-repeat="item in myitemlist" value=" {{item.value}}" >{{item.text}}</option>
</select>
Below is the code in controllers.js
var item = {};
item.value = "";
item.text = "--SELECT--";
$scope.myitemlist.push(item);
item = {};
item.value = "1";
item.text = "item 1";
$scope.myitemlist.push(item);
item = {};
item.value = "2";
item.text = "item 2";
$scope.myitemlist.push(item);
$scope.myselecteditem=$scope.myitemlist[2].value;
From the above code the selected item by default will be 'item2' But its '--SELECT--'. Not changing.
Upvotes: 2
Views: 1568
Reputation: 17647
The selected item (default or initial) must be one element of the items used in the ngOptions list, not only the value.
So you have to write:
$scope.myselecteditem=$scope.myitemlist[2];
Here is a working snippet:
angular.module('ionicApp', ['ionic'])
.controller('MyCtrl', function($scope) {
$scope.myitemlist = [];
var item = {};
item.value = "";
item.text = "--SELECT--";
$scope.myitemlist.push(item);
item = {};
item.value = "1";
item.text = "item 1";
$scope.myitemlist.push(item);
item = {};
item.value = "2";
item.text = "item 2";
$scope.myitemlist.push(item);
$scope.myselecteditem = $scope.myitemlist[2];
});
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic Template</title>
<link href="http://code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="http://code.ionicframework.com/nightly/js/ionic.bundle.js">
</script>
</head>
<body ng-controller="MyCtrl">
<ion-header-bar class="bar-positive">
<h1 class="title">Select</h1>
</ion-header-bar>
<ion-content padding="true">
<div class="list">
<div class="item item-input item-select">
<div class="input-label">
Test
</div>
<select ng-model="myselecteditem" ng-options="item.text for item in myitemlist track by item.value">
</select>
</div>
</div>
</ion-content>
</body>
</html>
Upvotes: 1