angularjs - How do I avoid repeating boilerplate code in angular controllers? -
Assume that I have three members: users, groups, pages All three have a template in which I can edit them, as well as other things that are unique to each other.
I know that there is almost the same code in each control, which violates repeated boilerplate and drill. The following pseudocode is:
self.editMode = false; // we are in ourselves to indicate Edit = function () {self.editMode = true;}; // self.save = function to enter edit mode {self.item.save (function)} {if (err) {// mark it properly} else {self.editMode = False; // successfully done // also put a "saved" message}}); }); Self.cancel = function (form) {self.item. $ Reset (); // Form Reset, Clear Entries, etc. Self.editMode = false; }; To do this, there is irreversibly repetitive in every controller. Is there a proper angular way to do this? I was probably thinking of a service to decorate the controller, but it seems that a strange use for the service seems a bit awkward.
Any better ideas?
UPDATE
> I think this decoration is suggesting Jussi?
mod.factory ('editing utility service', function) {return {makeEditable: function (ctrlr, item) {ctrlr.editMode = false; // to indicate we ctrlr.edit = function () {ctrlr.editMode = true;}; // are entering the edit mode in ctrlr.save = function {item.save (function (err) {if (Err) {// mark it properly on the form} and {ctrlr.editMode = False; // is done successfully // also put the message "saved"}}}}; Ctrlr.cancel = function (form) {items. $ Reset (); // Form Reset, Clear Entries etc. Ctrlr.editMode = false; }; }}; }). Controller ('MyCtrl', Function (Editable Ctrl + Service) {Editable Transmission Service. Make Edit (Self); // Everything Unique to this Controller}}}
A service is fine for this, it is quite similar to how you define resources. Just make sure the service works with those items Which includes its functionality instead of sending the scope of the service's controller.
Comments
Post a Comment