Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid code duplication when using controllers with similar methods?

Say I have following controllers:

controller("MyCtrl1", ["$scope", "$sce", "myService", "$location",
    function ($scope, $sce, myService, $location) {
        $scope.Resources = window.MyGlobalResorcesObject;
        $scope.trustedHtml = function (input) {
            return $sce.trustAsHtml(input);
        };
        $scope.startProcessing = function () {
            $scope.processingRequest = true;
        };
        $scope.endProcessing = function () {
            $scope.processingRequest = false;
            $scope.$apply();
        };
        //some MyCtrl1-specific code goes here
    }]).
controller("MyCtrl2", ["$scope", "$sce", "myService", "$location",
    function ($scope, $sce, myService, $location) {
        $scope.Resources = window.MyGlobalResorcesObject;
        $scope.trustedHtml = function (input) {
            return $sce.trustAsHtml(input);
        };
        $scope.startProcessing = function () {
            $scope.processingRequest = true;
        };
        $scope.endProcessing = function () {
            $scope.processingRequest = false;
            $scope.$apply();
        };
        //some MyCtrl2-specific code goes here
    }]); 

You see, code is duplicated.I want to reuse common code.
What is the common practice to achieve this?

like image 503
Kai Avatar asked Jun 22 '14 15:06

Kai


1 Answers

Use a common service:

module.factory('processing', function($sce) {
    function initialize($scope) {
        $scope.Resources = window.MyGlobalResorcesObject;

        $scope.trustedHtml = function(input) {
            return $sce.trustAsHtml(input);
        };

        $scope.startProcessing = function() {
            $scope.processingRequest = true;
        };

        $scope.endProcessing = function () {
            $scope.processingRequest = false;
            $scope.$apply();
        };
    }

    return {
        initialize: initialize;
    }
});

And then in your controllers:

controller("MyCtrl1", function($scope, processing) {
    processing.initialize($scope);
}
like image 145
JB Nizet Avatar answered Sep 17 '22 18:09

JB Nizet