How to use Angular-Xeditable's onBeforeSave / onAfterSave methods with more than $data as parameter
Asked Answered
F

1

10

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

The documentation primarily focuses on using onbeforesave and onaftersave for validation, and while it does show that it can be used to save things, the examples don't show how to pass anything more than $data (or $index) to your onbeforesave/onaftersave method. The samples show saving something like $scope.person, which is fine if you have one item.

But what if the 3rd person in a list of 30 was edited? You certainly don't want to have to save them all. How do you save just the object that was edited instead of everything in the array?

Flavoprotein answered 2/5, 2014 at 0:7 Comment(0)
F
16

The Angular-Xeditable docs don't make it quite clear, but it appears that $data (and $index) are just injected values and that you can pass pretty much anything you want to the save/validate methods. So what you ought to be doing is passing the object itself (or maybe just its id).

Given the following markup:

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

You'd then have the following code in your controller:

$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 then handle the save any way you like. You aren't bound to using just the $data or $index values that Angular-Xeditable supplies. 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 supplied ID value. You would, of course, have to change the updatePerson() method to instead expect an ID as the first param and the name and dohickey as 2nd and 3rd params.

Also note that if you use onBeforeSave instead of onAfterSave as I did here, p.name won't yet have the new value and you'd need to go back to using $data to get the new value.

Flavoprotein answered 2/5, 2014 at 0:7 Comment(1)
I've been trying your solution for the whole day, but i don't know what's wrong in my code. The X-Editable doc isn't that helpful. Your explanation gave me some good advance, but i still can't make the final save in my database, would you mind looking into my question here?Beard

© 2022 - 2024 — McMap. All rights reserved.