Your understanding is correct that Angular.js requires you to inject multiple services into the controller when using dependency injection. This is a fundamental aspect of a framework that utilizes constructor dependency injection. However, in the example you provided, you have the opportunity to refactor some of the services being injected. While you may still need to inject certain alternatives, you can streamline your code and reduce the amount of boilerplate code needed.
Optimizing Services
$scope
By utilizing the controllerAs
syntax, you can simplify your code by assigning properties directly to the controller and referencing it in your templates. Todd Motto and John Papa both advocate for this approach in their respective discussions on Angular.js best practices.
$http
It is advisable to avoid directly using $http in your controllers. Instead, create a service that abstracts the $http calls, similar to what the Post
service appears to be doing. John Papa's style guide highlights the benefits of this approach in terms of data services.
$modal
Abstracting the $modal functionality into separate services, such as a ConfirmModalService
, can help streamline your codebase. By centralizing logic related to modals, you can enhance code reusability. Additionally, storing modal HTML content in a separate file or property within the service can improve maintainability.
Additional Style Recommendations
To further simplify your controller, consider moving certain services into a separate abstraction layer responsible for handling user interactions. This modular approach offers flexibility in code organization.
Furthermore, relying on the global window
object can pose challenges during testing. In line with Angular.js best practices, consider injecting the angular $window
service for improved testability and adherence to recommended coding styles.
Sample Implementation:
lassoControllers.controller('PostsController', ['$timeout', 'Post', 'ConfirmModalService',
function($timeout, Post, ConfirmModalService) {
var vm = this;
vm.posts = Post.query();
vm.askDelete = function(item) {
var message = "Are you sure ?";
var modalResult = ConfirmModalService.open(message).then(function() {
vm.reallyDelete(item);
});
};
vm.reallyDelete = function(item) {
// Assuming this is an array
vm.items = vm.items.filter(function(elem) {
return elem != item;
});
};
}]);