简体   繁体   中英

How to use ngModelOptions and $rollbackViewValue() in AngularJS 1.3

I have a problem with my input fields in my modal view. When I take a change in the input fields then it is updating the table list but when I leave the page and go back to this page with the table list then die changes are disappeared.

This is my modal view:

<form class="form-horizontal" name="editForm" novalidate>
<div class="modal-body">
<div class="form-group-sm has-feedback">
  <label class="control-label">Firstname</label>
  <input type="text" 
         class="form-control" 
         name="Fname"
         ng-model="selected.fname" 
         ng-model-options="{updateOn: 'updateItem'}"
         ng-required="true"
         />
</div>
</div>
//the same input field for lastname
...
<div class="modal-footer">
  <button class="btn btn-default" ng-click="createItem(selected)" type="submit">Erstellen</button>
  <button class="btn btn-default" ng-click="updateItem(selected)"> Ändern</button>
  <button class="btn btn-default" ng-click="cancel()">Abbrechen</button>
</div>
</form>

Modal Ctrl:

$scope.cancel = function () {
  $scope.editForm.$rollbackViewValue();
  $modalInstance.dismiss('cancel');
}

$scope.updateItem = function (updateItem) {
  CrudService.update(updateItem);
  $scope.ok();
}

Crud Service:

...
update: function (updateItem) {
   updateItem.$update();
},
...

I have only seen examples of $rollbackViewValue() with one input field and the code: $scope.myForm.inputName.$rollbackViewValue() but I have more than one input fields?

you should call $rollbackViewValue() through the form name:

 editForm.$rollbackViewValue()

call it in your template:

{{editForm.$rollbackViewValue.toString()}} 

and you will see how it actually works:

function () { 
     forEach(controls, function(control) { 
        control.$rollbackViewValue(); 
     }); 
}

A little late but for others reference (I came across this looking for another issue with $rollbackViewValue).

Using $rollbackViewValue in controller: to use $scope to reference the form from the controller, you have to use the ng-form attribute on a child element of the form (like for instance the form-group div in your example).

That makes $scope.editForm.$rollbackViewValue() available in the controller and resets the entire form.

For cases where buttons are inside the form, using ng-submit and ng-model-options="{ updateOn: 'submit' }" on input fields, then adding 'type=button' attribute to cancel button element (so submit isn't triggered) is a quick solution.

Example: https://embed.plnkr.co/IQ4vvutC3tcHvVBH0821/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM