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

前端 未结 1 579
醉梦人生
醉梦人生 2021-01-04 23:41

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

相关标签:
1条回答
  • 2021-01-05 00:07

    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.

    0 讨论(0)
提交回复
热议问题