Search code examples
javascriptangularjspass-by-referencengmodel

javascript force update on ng-model value on inputbox


<form>
      Low: <input type="number" name="lowRange" 
            ng-model="weight" ng-model-options = "{updateOn:'submit'}">
      <button type="submit">Assign</button>
      <button type="button" ng-click="resetValue()">Discard</button>
</form>
<p>$scope.weight: {{weight}}</p>

weight is binded with ng-model. By using ng-model-options="{updateOn:'submit'}", the ng-model value is only updated after clicking on submit button.
When user modified the value in the input, and click discard, I want to reset the value inside the inputbox to be the current ng-model value.
I'm doing it by having a ng-click="resetValue()"

$scope.resetValue = function(){
    $scope.weight = $scope.weight; //if +1 here will update ng-model
  }

But the assignment does not work when the variables are the same. Possibly because it is assigning by reference.
The value in the inputbox is not changed. Does anyone have any idea on how to force the ng-model on the inputbox to update the value?

Here is a demo: http://plnkr.co/edit/NQTieUmdEbxZeBsjk8Jw?%2F=preview&p=preview


Solution

  • You need to tell the input field to reset.

    <form name="myForm">
      Low: <input type="number" name="lowRange" ng-model="weight" ng-model-options = "{updateOn:'submit'}">
      <br>
      <button type="submit">Assign</button>
      <button type="button" ng-click="myForm.lowRange.$rollbackViewValue();">Discard</button>
    </form>