2014-04-09 126 views
3

我试图向用户显示一些可编辑的结果,所以我通过输入字段显示它们。这是我在做什么一个基本的例子:如何动态更改输入值

<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,我使用的标签是否被正确的得到的结果进行测试,它是。但是,如果我编辑firstsecond值,输入的result不会更新。

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

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

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

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

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

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

在此先感谢。

回答

5

当用户编辑结果输入时,你想要发生什么?你想要数据绑定中断吗(我不假设并忽略这种可能性)?你想让其中一个输入调整到适当的值吗?

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

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

而在你的看法:

{{ result() }} 

但是,如果你希望用户能够编辑(结果 - 第一),然后你想在你的视图中这样的东西(顺便说一下,请注意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; 
} 
+0

非常感谢您对这个答案+1 –

+0

只需要调整两个字符,以适应乘。谢谢! – Antoine