3

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.

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Only had to adjust two characters to accommodate multiplication. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.