我有一个select
应该将myCoef
跟踪为 float 值(不是对象,而是浮点值)。
我有以下代码(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>
&#13;
如何正确初始化select
,以便在myCoef中保留浮点值?
答案 0 :(得分:1)
使用As语法并删除track by。
PS:如果有人知道为什么我必须删除曲目,他可以编辑我的答案,因为我真的不知道为什么。
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>
答案 1 :(得分:0)
有点奇怪的语法。在Walfrat answer之后,示例如何通过val初始化,或者通过名称初始化值(不通过$scope.myCoef = $scope.coefs[1]
语法)
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>