As a newcomer to angularjs, I have a question about controllers and functions. I understand that typically there is one controller for one view, but multiple controllers can be used for a single view. In my case, I have two controllers in a single view and a function called addComma that I want to make reusable across all controllers on the same view or even different views. How can I make a function in a controller accessible globally throughout my application? Apologies if this seems like a basic question, I'm still trying to grasp the concepts of angularjs.
app.controller("GetChargesController", function ($scope, GetService, $rootScope) {
$scope.Title = "Charges Details List";
$rootScope.loading = true;
// Call Service Method here
$scope.GetChargesDetails = GetService.GetAll("CommonApi", "GetChargesDetails").then(function (d) {
$scope.ChargesDetails = d;
$rootScope.loading = false;
});
// Add comma function here
$scope.addComma = function(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
});
app.controller("GetPaymentsController", function ($scope, GetService, $rootScope) {
$scope.Title = "Payments Details List";
$rootScope.loading = true;
// Call Service Method here
$scope.GetPaymentsDetails = GetService.GetAll("CommonApi", "GetPaymentsDetails").then(function (d) {
$scope.PaymentsDetails = d;
$rootScope.loading = false;
});
// Add comma function here
$scope.addComma = function (x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
});
Below is a generic service I've created to retrieve data from a database using asp.net web api. Angular services can hold data so we don't need to repeatedly call the database when navigating between links. For example, if I have Home Link, PaymentCharges Link, and Orders Link on a page, clicking back and forth should not trigger unnecessary database calls. It seems like caching the data would prevent these extra calls.
app.factory("GetService", function ($http) {
var thisService = {};
// Retrieve all data from database
thisService.GetAll = function (controllername, methodName) {
var promise = $http({
method: 'GET',
url: '/api/'+controllername + '/' + methodName
})
.then(function (response) {
return response.data;
},
function (response) {
return response.data;
});
return promise;
};
});