I have an authentication panel directive that controls the display of
signin, signup and reset password forms. The state of the panel - open or
closed and which of the three forms should currently be displayed - needs
to be controlled from multiple places within my app. So i decided to move
the directive's state logic into a separate service, that can then be
injected wherever needed.
Using the methods of the service to modify the directives state feels
clean, but i'm not 100% sure of how best to deal with exposing the
properties/functions of the service to the view/html.
This is simplified version of the service:
app.service('authPanelService', function() {
this.isOpen = false;
this.doSomething = function() {
...
}
});
As i see it, i have 2 options for exposing the service to the view/html
within a controller.
1) Simply set the service as a property of the controller, so that it's
properties/methods are then directly exposed to the view/html (i'm using
the controllerAs syntax):
app.controller('AppCtrl', function(authPanelService) {
var vm = this;
vm.authPanelService = authPanelService;
});
<div ng-controller='AppCtrl as appCtrl'>
<some-directive do-something='appCtrl.authPanelService.doSomething()'>
{{appCtrl.authPanelService.isOpen}}</some-directive>
</div>
2) Explicitly mirror the API of the service within the controller, to proxy
calls to the service:
app.controller('AppCtrl', function(authPanelService) {
var vm = this;
vm.isOpen = function() {
return authPanelService.isOpen;
};
vm.doSomething = function() {
authPanelService.doSomething();
};
});
<div ng-controller='AppCtrl as appCtrl'>
<some-directive do-something='appCtrl.doSomething()'>
{{appCtrl.isOpen()}}</some-directive>
</div>
*Thoughts on solutions.*
1) Feels wrong, as i feel like the controller should explicitly expose an
API for the view to consume, thus clearly stating it's
intentions/functionality.
2) Consider the fact that in reality the service API is actually bigger
than shown. (Just writing this seems stupid as it's the proxy pattern) Does
this implementation break DRY?
It also feels strange that any property of the service (unless i'm missing
something?), would need to be exposed within the controller as a method.
And then defined withing the markup as a method call i.e appCtrl.isOpen()
*Questions.*
1) Is a separate service that manages the display state of the directive
the best solution for this scenario?
2) Which of the two proposed solutions would be considered better? What are
the pros and cons of both (that i haven't thought of)?
Thanks.
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.