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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With