hazimIskandar hazimIskandar - 8 months ago 37
AngularJS Question

How to convert value by only using ng-options in angular

I want to convert the values that I get from equation to cm/mm/inch by only choose from the ng-options and it will automatically update. any idea how I can do that by using only selection from ng-options without use any button?

here are the sample of code


<select ng-model = "length.selectedUnit" ng-options="x.unit for x in velogas1.availableUnits track by x.unit">


$scope.length = {
availableUnits: [
{unit: 'mm'},
{unit: 'cm'},
{unit: 'Inch'},
{unit: 'm'}
selectedUnit: {unit: 'm'}



You can use ng-change on the select to fire your calculation function.

Edit: If you change your options to include the multipliers, then you can let the calculations work in the interpolator without the need of ng-change.

angular.module('test', []).controller('Test', Test);

function Test($scope) {
  $scope.value = 3.18; // in meter
  $scope.units = [
    {name: 'm', multiplier: 1},
    {name: 'inch', multiplier: 39.3701},
    {name: 'cm', multiplier: 10},
    {name: 'mm', multiplier: 100}
  $scope.selectedUnit = $scope.units[0];
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.1/angular.min.js"></script>

<div ng-app='test' ng-controller='Test'>
  <div>{{ value * selectedUnit.multiplier }} {{selectedUnit.name}}</div>
  <select ng-model="selectedUnit" ng-options="unit as unit.name for unit in units"></select>