在AngularJs中初始化一个选择

时间:2016-04-27 09:11:22

标签: angularjs

我有一个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;
&#13;
&#13;

如何正确初始化select,以便在myCoef中保留浮点值?

2 个答案:

答案 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>