Reputation: 5638
I'm trying to keep a controller of my Angular application thin. I extracted the data logic and move them into the service. I wonder whether it's also acceptable to move the UI logic that is coupled with the data logic into the service (example: displaying a form in a modal before posting form data to the server)?
For example
angular.module('App').service('DocumentService', function($modal, $q, $http) {
var modalPromise = {
template: 'newDocumentForm.html',
persist: true,
show: false,
scope: $scope
};
this.createNewDocument = function() {
// show form in modal
}
this.submitDocument = function() {
// submit new document using $http
}
})
Upvotes: 0
Views: 209
Reputation: 42497
There are two sides to this coin.
The first side is obvious: yes, you can use $modal
in a service. $modal
on has one method, open()
. The particulars of the view involved in displaying your modal can be safely segregated from consumers and communicate back using the result
or opened
promises obtained from the promise returned by open
, and of course you also have eventing at your disposal to keep the modal and consumers loosely coupled.
The flip side to that coin is that services are not usually the best place to encapsulate logic for UI because they are UI agnostic and thus not part of the view pipeline, and can be stubbornly inflexible or hard to manipulate in your UI workflows. Sometimes people misunderstand services as merely being a place to consolidate reusable code and inject them into consumers. IMHO, they represent a state and/or resource that is shared between components in an application.
That being said, if your particular use case is straight forward enough and detached from any particular UI workflow, it may be fine for you to just manage the modal in the service.
For example, you may wish to enforce a confirmation/alert dialog before deleting a document, and it is dubious as to whether or not there is any benefit in separating that dialog into a concern for each controller that lets you perform a delete. The issue is whether or not you start piling numerous and/or more complicated UI for other events surrounding documents and trying to decouple them from how they are used at various points in the application.
Upvotes: 1