I'm seeking advice on dependency injection in Angular. Is there a way to instruct Angular not to inject all dependencies requested, preventing it from throwing an error? My scenario involves using a controller for both a regular route (/addPlayer) and a modal for adding players. The challenge arises when I need $modalInstance injected for the modal but not for the regular route. How can I achieve this without encountering errors? Let me provide more context:
In a page (/sportsTeams, controlled by SportsTeamsCtrl), users can select players from a list. An option "--- Add New Player ---" triggers opening a modal for adding a player.
Here is a simplified version of my code:
The controller for the sportsTeams page manages player selection/addition. It includes a function that utilizes the 'ModalsService' I created for launching modals to add players across different pages without redundancy.
App.controller('SportsTeamsCtrl', function($scope, ModalsService) {
$scope.selectOption = function(option) {
if (option == '--- Add New Player ---') {
ModalsService.launchPlayerModal().then(function(newOption) {
$scope.player = newOption;
}, function(err) {
console.log(err);
});
}
}
}
The 'ModalsService' implementation:
App.factory('ModalsService', function($modal, $q) {
var launchPlayerModal = function() {
var deferred = $q.defer();
var modalInstance = $modal.open({
templateUrl: '/partials/addPlayer.html',
controller: 'AddPlayerCtrl',
size: 'lg',
resolve: {
isModal: function() {return true;}
}
});
modalInstance.result.then(function(selectedPlayer) {
deferred.resolve(selectedPlayer);
}, function() {
deferred.reject();
console.log('modal dismissed at ' + new Date());
});
return deferred.promise;
};
}
The issue I face lies within 'AddPlayerCtrl', where I want to use the same controller for both modal instances and regular routes to '/addPlayer':
App.controller('AddPlayerCtrl', function($scope, isModal, $modalInstance) {
$scope.isModal = isModal;
$scope.addPlayer = function(player) {
addPlayerToDatabase(category).then(function(data) {
if ($scope.isModal) {
$modalInstance.close(data);
}
}, function(err) {
console.log(err);
});
};
}
The problem arises because $modalInstance needs to be injected only for modal usage, not for regular routes. This leads to an error when accessing '/addPlayer'. How can I conditionally inject $modalInstance or any other service based on the context?
While suggestions may include having separate controllers for '/addPlayer' routes and modals loading 'addPlayer' content, I am curious about alternative approaches that might be more efficient.