2017-05-05 67 views
0

我的文本框看起来像这样如何更改无线电值更改文本框的ng模型?

<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 。我该如何实现这个目标?我也想更新文本框的最小和最大值。

+0

你能不能有这样的事[这](http://plnkr.co/edit/PUfnCyVsb3dlrRhuIUnL?p=preview)? – tanmay

+0

不幸的是没有...我必须将celcius和farheneit传递给api。其中一个为空,另一个包含一个值。 –

+0

我更喜欢简单的UI东西,而不是一些复杂的东西(比如你想要做什么),并且在调用API之前修改了对象..不是你所要求的很难做到,它更简洁(并且可维护)?另一种方法.. – tanmay

回答

1

试用obj[obj.selection]

请参阅下面的代码片段。

angular.module("app", []) 
 
    .controller("myCtrl", function($scope) { 
 
    $scope.obj = { 
 
     selection: 'celcius', 
 
     celcius: 1, 
 
     farheneit: 2 
 
    }; 
 
    });
<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>

1

我已经创建了下面的代码片段。暂时我添加了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>