如何在 angularjs 中将码值转换为米值

How to convert yard value to meter value in angularjs

我正在尝试将仪表值转换为码。我有两个下拉菜单。第一个下拉菜单有一些值。第二个下拉列表有两个值 "meter" & "yard",现在的问题是如果从第二个下拉列表中选择 meter,第一个下拉列表中的值想要保持不变。但是,如果 "Yard" 选择了第一个下拉列表中的全部值,则需要将其转换为 Yard 值。我找到了逻辑,但我不知道如何将它实现到 angular 控制器中。我在这里创建了一个 plunkr https://plnkr.co/edit/Q4lxXf6YRrdAV2kUNAln?p=preview

HTML

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@1.6.2" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
   <div ng-app="app" ng-controller="ctrl">

 <select class="form-control" ng-model="distancetypeId" ng-options="Distance.id as Distance.value for Distance in data"></select>
<select class="form-control" ng-model="ConverttypeId" ng-options="Convert.id as Convert.type for Convert in convertor" ng-change="convertToMeter()"></select>

</div>
  </body>

</html>

AngularJS

angular.module("app",[])
.controller("ctrl",function($scope){


    $scope.data = [{
    "id": 1,
    "value": 254
  },
  {
    "id": 2,
    "value": 100
  },
  {
    "id": 3,
    "value":250 
  },
  {
    "id": 4,
    "value":10 
  }]

    $scope.convertor = [{
    "id": 1,
    "type": "Meter"
  },
  {
    "id": 2,
    "type": "Yard"
  }];



 $scope.convertToMeter=function(ConverttypeId){
           if(ConverttypeId = 2){

    //this is logic that i want to do  (dropdown1values=value*1.0936;)

 }}

 });

因此,如果选择 Yard,则需要将距离值乘以 1.0936,这样您就可以直接在 ngOptions 中这样做:

ng-options="Distance.id as (Distance.value * (1 + (ConverttypeId == '2') * 0.0936)) for Distance in data"

因此,如果 Converttypeid 等于 '2'(这意味着选择了 Yard 选项),则距离乘以 1 + (true * 0.0936) 等于 1.0936

如果不是,则距离乘以 1 + (false * 0.0936) 等于 1,所以它仍然是相同的值。

Here is a plunker 显示这个

你可以像这样修改ng-change函数

 $scope.convertToMeter=function( ){
    if($scope.ConverttypeId == 2){
    // document.getElementById("outputMeters").innerHTML=value/1.0936;
      for(var i=0; i<=$scope.data.length-1; i++){
        $scope.data[i].value =( $scope.data[i].value/ 0.9144 ).toFixed(2)
      }
    }else if($scope.ConverttypeId == 1){
      for(var i=0; i<=$scope.data.length-1; i++){
        $scope.data[i].value = parseInt($scope.data[i].value * 0.9144) 
      }
    }

 }

Demo