2014-04-09 128 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