Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 210
shaunlim Avatar asked Oct 09 '12 02:10

shaunlim


1 Answers

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

like image 178
Dan Doyon Avatar answered Oct 15 '22 19:10

Dan Doyon