2016-04-27 95 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>