Peter Nixey Peter Nixey - 4 months ago 18x
AngularJS Question

Can you have a custom trigger for updating ng-model fields in Angular?

Angular has a number of options for delaying the update to a model based on events in an input field:

<input type="text" name="username"
ng-model-options="{updateOn: 'default blur',
debounce: {default: 500, blur: 0} }" />

(See ng-model options)

Can you delay all the commits to the object based on a user confirmation?

The basic options that Angular offers allows the editing of an input form to be decoupled from the actual update of the model. There are some nice bonuses with this in that we can roll the value of the object back if we decide to cancel that update.

However, I would like to delay the update of the model, not based on an event on the input field but instead based on someone clicking a submit button.

I would ideally like a form where the user can update the inputs (let's say for a
form, any bound elements in the page
etc. do not update and then when the user clicks submit those updates get committed to the model.

Equally if the user clicks "Cancel" the updates can all be rolled back.

Ideal setup:

<input type="text" name="username"
ng-model-options="{updateOn: 'myCustomEvent' }" />

<button onClick="broadCastMyCustomEventIntoForm()">Save changes</>

Is this possible?


Yes it is possible as long as you bind your input fields to custom event and then trigger that custom event on user confirmation.

<input bind-event type="text" name="userName" ng-model="" ng-model-options="{ updateOn: 'customEvent'}" />

  //bind-event directive for input fields. 
  .directive('bindEvent', function() {
      return {
        restrict: 'EAC',
        controller: function($scope, $element, $attrs) {

          $element.on('customEvent', function() {
            console.log('custom event is triggered');

    //trigger the event on submit.
    $ = function() {
      $element.find( "input" ).triggerHandler( "customEvent" );