Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change input value

Tags:

angularjs

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>

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...

Thanks in advance.

like image 221
Sergio Carneiro Avatar asked Feb 16 '26 23:02

Sergio Carneiro


1 Answers

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; }

And in your view:

{{ 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">

And in your controller:

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

$scope.adjustInput = function() {
  $scope.second = $scope.result - $scope.first;
}
like image 86
Robert Balicki Avatar answered Feb 19 '26 19:02

Robert Balicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!