Reputation: 15229
I have a select
that should track a myCoef
as a float value(not an object, but a float value).
I have the following code (CodePen HERE):
function theController($scope) {
$scope.coefs = [
{name:'mm', val:1/1000},
{name:'cm', val:1/100},
{name:'m', val:1}
];
$scope.myCoef = 1/100;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<body ng-app>
<div ng-controller="theController">
<select ng-model="myCoef"
ng-options="coef.name for coef in coefs track by coef.val">
</select>{{myCoef}}
</div>
</body>
How do I correctly initialise my select
, in order to keep a float value in myCoef?
Upvotes: 0
Views: 26
Reputation: 15229
A little strange syntax. Following the Walfrat answer, examples how to init by val, or by name the initial value (without passing via $scope.myCoef = $scope.coefs[1]
syntax)
function theController($scope) {
$scope.coefs = [
{name:'mm', val:1/1000},
{name:'cm', val:1/100},
{name: 'm', val:1}
];
$scope.myCoefVal = 1/1000;
$scope.myCoefName = 'cm';
}
<body ng-app>
<div ng-controller="theController">
Init by value - myCoefVal=1/100 <br>
<select ng-model="myCoefVal"
ng-options="coef.val as coef.name for coef in coefs">
</select><br>
now myCoefVal={{myCoefVal}}
<br/><br/>
Init by name - myCoefName='cm'<br>
<select ng-model="myCoefName"
ng-options="coef.name as coef.name for coef in coefs">
</select><br>
now myCoefName='{{myCoefName}}'
</div>
</body>
Upvotes: 0
Reputation: 5353
Use As syntax and remove track by.
PS : If someone knows why i have to remove track by he can edit my answer because i don't really know why.
function theController($scope) {
$scope.coefs = [
{name:'mm', val:1/1000},
{name:'cm', val:1/100},
{name:'m', val:1}
];
$scope.myCoef = 1/100;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<body ng-app>
<div ng-controller="theController">
<select ng-model="myCoef"
ng-options="coef.val as coef.name for coef in coefs">
</select>{{myCoef}}
</div>
</body>
Upvotes: 1