2016-04-27 70 views
0

我有一个select应该跟踪myCoef作为浮点数值(不是一个对象,而是一个浮点值)。在AngularJs中初始化一个选择

我有以下代码(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>

如何正确初始化我select,为了保持在myCoef的浮点值?

+0

{{myCoef.val}}? – Sajal

+0

我希望将myCoef作为** float **值,而不是一个对象。 – Serge

回答

1

使用As语法并删除轨道。

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>

+0

然而,选择将不会正确初始化与“cm”值... – Serge

+0

奇怪..我添加删除轨道的工作...检查我编辑的答案 – Walfrat

+0

超级!我不太了解这个语法,但似乎工作!您可以立即删除incorect第一次编辑;) – Serge

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>