In my Angular application setup, I have an "Edit Invitation" state where a single invitation is scoped. This invitation contains a list of guests controlled by a guestList controller and iterated over in the view.
<div ng-controller="guestListCtrl as guestList">
<div ng-repeat="guest in invitation.guests">
{{ guest.name }}
</div>
</div>
At the end of the guest list, there is a button to add a new guest. Clicking this button toggles a small form for users to save a new guest record.
<form name="addGuest" class="form" ng-submit="addGuest.$valid && guestList.addGuest(guestList.newGuest)" novalidation>
The controller successfully handles adding a new guest and pushing it onto its parent scope, guestList.guests.
However, on the Admin page, I have a similar setup with a guestList controller displaying a list of guests and allowing for adding a new guest through the same form. The HTML structure here differs significantly - utilizing different elements, CSS classes, and a directive for field editing by admins.
My query is whether there is a way to extract the "add new record" functionality into its own partial or directive to avoid rewriting the form and logic each time.
One potential solution could be creating an element directive:
<new-guest></new-guest>
Below is the directive implementation:
angular.module('app.directives').directive('newGuest', ['Guest', '$stateParams', function(Guest, $stateParams){
return {
restrict: 'E',
transclude: true,
templateUrl: 'directives/new-guest.html',
bindToController: true,
controllerAs: 'newGuestCtrl',
controller: function() {
var vm = this
vm.newGuest = { "invitation_id": $stateParams.id };
vm.addGuest = function(newGuest){
Guest.create({guest: newGuest}, function(response) {
//push new guest onto parent scope here
});
vm.newGuest = {};
};
}
}
}]);
The directive effectively adds records to the database but struggles to push the new data onto the parent scope outside the directive (guestList.guests). One possible approach would involve creating a new directive housing the guest list and pushing onto that directive's scope, but this may not be ideal considering the distinct HTML structures used for Admin and User versions of the guest list.