AngularJS: Data-bound modal – save changes only when "Save" is clicked, or forget changes if "Cancel" is clicked

All we need is an easy explanation of the problem, so here it is.

I have a list of items, and upon clicking on one of the items, a modal dialog is displayed for the user to make some changes and click either “Close” or “Save changes”.

The problem is that say that user makes some changes and clicks on “Close”, the changes would have been reflected in the model the view is bound to, since data-binding is instant.

My question is then, how do I either defer the updates and only perform binding when “Save Changes” is clicked, or somehow forget the changes if “Cancel” is clicked.

The code for my modal dialog is like so:

<div ui-modal class="fade static" ng-model="modalShown" id="myModal" data-backdrop="static">
        <div class="modal-header">
            <button type="button" class="close" ng-click="closeModal()" aria-hidden="true">&times;</button>
            <h3>{{selectedClientFeature.feature.type}}</h3>
        </div>
        <div class="modal-body">    
            <ul class="unstyled columnlist">
                <li ng-repeat="country in countriesForEdit">
                    <input type="checkbox" ng-model="country.selected"> {{country.name}}
                </li>
            </ul>
        </div>
        <div class="modal-footer">
            <a ng-click="closeModal()" class="btn">Close</a>
            <a ng-click="saveChanges()" class="btn btn-primary">Save changes</a>
        </div>
    </div>

Thanks,
Shaun

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The angularjs doc use to have an example of just this situation. What you would need is to clone your model (see angular.copy), prior to showing your edit modal, and when a user clicks on closeModal() you would reassign your model to the cloned value. IMHO, i would rename your ‘Close’ button to ‘Cancel’ and put it to the right of ‘Save Changes’, this is more explicit and seems to be the way many sites work.

Hope this helps

–dan

Method 2

To automate manual cloning/updating model I came up with lazy-model directive.
See https://stackoverflow.com/a/20643001/740245

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply