How to use Angular -Xeditable onBeforeSave / onAfterSave methods with more than $ data as a parameter

When using Angular -Xeditable for the first time with my application, I ran into a problem trying to figure out how to save a change to an x-editable object that was accessed through an ng-repeat loop.

Most of the documentation focuses on using onbeforesave and onftersave for validation, and although it shows that it can be used to save things, the examples don't show how to pass more than $ data (or $ index) to your onbeforesave / onftersave method. The samples show the preservation of something like $ scope.person, and this is fine if you have one element.

But what if the 3rd person in the list of 30 is edited? Of course, you do not want to be saved. How to save only the object that has been edited, and not everything in the array?

+8
javascript angularjs x-editable
source share
1 answer

Angular -Xeditable docs do not make this clear enough, but it looks like $ data (and $ index) are just entered values โ€‹โ€‹and that you can pass almost anything you want for save / check methods. So what you have to do is pass the object itself (or maybe just its identifier).

Given the following markup:

<div ng-repeat="p in people"> <a href="#" editable-text="p.name" onaftersave="updatePerson(p)">{{p.name}}</a> </div> 

Your controller will have the following code:

 $scope.updatePerson = function(person) { var ret = PersonService.save(person); // or whatever save mechanism you use // You need to return a error string if save fails, true otherwise if (ret !== null) { // You have to make sure this logic works for your save service return ret; } return true; } 

With this, you can handle the save in any way. You are not required to use only the $ data or $ index values โ€‹โ€‹that Angular -Xeditable supplied. You could just as easily do something like this:

 <div ng-repeat="p in people"> <a href="#" editable-text="p.name" onaftersave="updatePerson(p.id, p.name, p.dohickey)">{{p.name}}</a> </div> 

And update only the name and dohickey fields for the person with the specified ID value. Of course, you would have to change the updatePerson () method to instead expect the identifier to be the first parameter, and the name and dohickey to be the second and third parameters.

Also note that if you use onBeforeSave instead of onAfterSave, as I am here, p.name will not get a new value yet, and you will need to return to using $ data to get the new value.

+14
source share

All Articles