2014-06-22 69 views
5

說我有以下控制器:如何在使用類似方法的控制器時避免代碼重複?

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

你看,代碼是duplicated.I要重用通用代碼。
實現此目標的常見做法是什麼?

回答

8

使用一個共同的服務:

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

然後在你的控制器:

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