如何动态地改变输入值 [英] How to dynamically change input value

查看:118
本文介绍了如何动态地改变输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想展示一些可编辑的结果给用户,所以我告诉他们通过输入字段。这是我在做什么的一个基本的例子:

I'm trying to show some editable results to the users, so I show them through an input field. This is a basic example of what I'm doing:

<div class="form-group">
    <label>First number</label>
    <input type="text" ng-model="first" ng-required="true" class="form-control">
</div>

<div class="form-group">
    <label>Second number</label>
    <input type="text" ng-model="second" ng-required="true" class="form-control">
</div>

<div class="form-group">
    <label>The sum is: {{first + second }}</label>
    <input type="text" ng-model="result" ng-required="true" class="form-control">
</div>

在结果的DIV,我使用的标签是否被正确得到的结果进行测试,它是。但是,如果我修改第一第二值,输入的结果不更新。

In the result's div, I used a label to test if the result is being obtained correctly, and it is. But if I edit the first or second values, the input's result doesn't update.

这是所使用的控制器(是的,形式是一个模式):

This is the controller used (yeah, the form is in a modal):

var ModalInstanceCtrl = function ($scope, $modalInstance) {

   $scope.result = $scope.first + $scope.second;

   $scope.confirm = function () {
      $modalInstance.close(result);
   };

   $scope.cancelNewBet = function () {
      $modalInstance.dismiss('cancel');
   };
};

我认为价值应该得到自动更新一次我定义它是如何获得的。但显然它错过一些改变,通过脚本的结果...

I thought the value was supposed to get automatically updated once I define how it is obtained. But clearly it misses something to change the result through script...

先谢谢了。

推荐答案

你想要什么,当用户编辑结果输入的情况发生?你想要的数据绑定打破(我假设没有,而忽略这种可能性)?你想的一个输入来调整到适当的值α

What do you want to happen when the user edits the results input? Do you want the data binding to break (I assume not and ignore this possibility)? Do you want one of the inputs to adjust to the proper value?

如果您只想显示输出,这样做,在你的控制器:

If you only want to display the output, do this, in your controller:

$scope.result = function() { return $scope.first + $scope.second; }

而在你的看法:

{{ result() }}

但是,如果你希望用户能够编辑的结果,(假设)有次分配(结果 - 第一),那么你会希望在您的看法是这样的(顺便说一句,注意类型=号):

But if you want the user to be able to edit the result and (let's say) have second be assigned (result - first), then you'd want something like this in your view (by the way, note the type="number"):

<input type="number" ng-change="adjustResult()" ng-model="first">
<input type="number" ng-change="adjustResult()" ng-model="second">
<input type="number" ng-change="adjustInput()" ng-model="result">

和在你的控制器:

$scope.adjustResult = function() {
  $scope.result = $scope.first + $scope.second;
};
$scope.adjustResult(); // initialize result

$scope.adjustInput = function() {
  $scope.second = $scope.result - $scope.first;
}

这篇关于如何动态地改变输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆