Search code examples
angularjsdata-bindingangular-ngmodeltwo-way

Angular ngModelOptions - bind value to model only when button is clicked


I have an input field that is bound to a model object, which I don't want to bind until the user clicks a button. I went through ng-model-option and updateOn, but seems they trigger only on out of the box JS events like blur and focus.

<input ng-model="modelobject" ng-model-options="{updateOn: confirmButtonClick}">

<button id="confirmButton" role="confirm" ng-click="confirmButtonClick == true" class="confirm-btn">Confirm</button>

How can I make the value bind to the model only upon the click of the button or a custom function? Would I need to write a custom directive?


Solution

  • You could do solve your problem by wrapping you fields inside a form and then update ng-model on submit of a form like ng-model-options="{updateOn: 'submit'}".

    HTML

    <form name="myForm">
      <input ng-model="modelobject" ng-model-options="{updateOn: 'submit'}">
      <button id="confirmButton" role="confirm" class="confirm-btn">
        Confirm
      </button>
    </form>
    

    Working Plunkr