0

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?

1
  • I'would like to have myCoef as float value, not an object. Commented Apr 27, 2016 at 9:15

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Strange.. i add to remove the track by to have it working... Check my edited answer
super! I don't really understand this syntax, but seem to work! you can remove the incorect first edit now ;)
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.