bfredo123 bfredo123 - 1 year ago 81
AngularJS Question

Best way to factorize controller code using $scope

My AngularJS 1 (+Ionic) application is handling various types of data (Employee, Company, ...), and there is one controller for each type and view.

Currently there is a lot of code identical between controllers, for instance the piece below used to delete an entity with a modal dialog box for confirmation.

I would like to factor this into one function or service or whatever, that I would call from each controller, but don't know what to do as this code is using $scope, $ionicModal and $ionicHistory.

Could you please tell me how to proceed? Many thanks!

$ionicModal.fromTemplateUrl("templates/delete-modal.html", {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
$scope.text = "Delete entity?";

$scope.delete = function() {
$scope.doDelete = function() {
$scope.doCancel = function() {

Answer Source

In this case, you're permitted to pass in $scope to the service methods. $ionicModal and $ionicHistory should be injected.

So create a service that injects $ionicModal and $ionicHistory. Defined your methods on the service, taking in $scope as an argument.

In each controller, pass in the $scope to the respective function of the service method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download