Kai
Kai

Reputation: 2073

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?

Upvotes: 5

Views: 1267

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

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);
}

Upvotes: 8

Related Questions