使用具有类似方法的控制器时如何避免代码重复?

时间:2014-06-22 15:07:23

标签: angularjs angularjs-controller

说我有以下控制器:

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

你看,代码是重复的。我想重用公共代码  实现这一目标的常见做法是什么?

1 个答案:

答案 0 :(得分: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);
}