如何在更改无线电值时更改文本框的ng-model?

时间:2017-05-05 05:22:58

标签: angularjs

我的文本框看起来像这样

    <input type="number" ng-model="obj.celcius" min="0" max="100" >

我有两个单选按钮

    <input type="radio" ng-model="obj.selection" value="celcius">
    <input type="radio" ng-model="obj.selection" value="farheneit">

当用户点击farheneit单选按钮时,我希望文本框的ng模型更改为obj.farheneit。我该如何实现这一目标?我还想更新文本框的最小值和最大值。

2 个答案:

答案 0 :(得分:1)

尝试使用obj[obj.selection]

请参阅下面的代码段。

&#13;
&#13;
angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.obj = {
      selection: 'celcius',
      celcius: 1,
      farheneit: 2
    };
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <input type="number" ng-model="obj[obj.selection]" min="0" max="100" >
  <input type="radio" ng-model="obj.selection" value="celcius">
  <input type="radio" ng-model="obj.selection" value="farheneit">
  
  {{obj.selection}}
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我在下面创建了代码段。暂时我为 Celsius Fahrenheit 添加了随机minmax值。

var app = angular.module('app', []);

app.controller('test', function($scope) {
  $scope.tempdata = {
    "celsius": {
      "min": 0,
      "max": 100,
      "value": 37
    },
    "fahrenheit": {
      "min": 50,
      "max": 150,
      "value": 120
    }
  }
  $scope.upDateData = function(data, type) {
    $scope.obj.temp = data;
    if (type == 'celsius') {
      $scope.min = $scope.tempdata.celsius.min;
      $scope.max = $scope.tempdata.celsius.max;
    } else if (type == 'fahrenheit') {
      $scope.min = $scope.tempdata.fahrenheit.min;
      $scope.max = $scope.tempdata.fahrenheit.max;
    }
  }
});
.text-data {
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
  Number:
  <input type="number" class="text-data" ng-model="obj.temp" min="{{min}}" max="{{max}}">
  <div>
    Celsius:
    <input type="radio" ng-model="obj.selection" ng-value="tempdata.celsius.value" ng-change="upDateData(obj.selection, 'celsius')"> Fahrenheit:
    <input type="radio" ng-model="obj.selection" ng-value="tempdata.fahrenheit.value" ng-change="upDateData(obj.selection, 'fahrenheit')">
  </div>
</div>