2014-06-22 17 views
5

Dire che ho seguenti controller:Come evitare la duplicazione del codice quando si utilizzano i controller con metodi simili?

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

Vedete, il codice è duplicated.I vuole riutilizzare il codice comune.
Qual è la pratica comune per raggiungere questo obiettivo?

risposta

8

Utilizzare un servizio comune:

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

E poi nel vostro controller:

controller("MyCtrl1", function($scope, processing) { 
    processing.initialize($scope); 
} 
Problemi correlati