There are two approaches to achieving this:
1. Developing and Implementing an AngularJS Service:
Here is a comprehensive example demonstrating the creation of an AngularJS Service and its utilization in various Controllers:
//AngularJS Module
var app = angular.module("Demo", ["ngRoute"])
//AngularJS Route Configuration
app.config(function($routeProvider, $locationProvider) {
$routeProvider.caseInsensitiveMatch = true;
$routeProvider.when("/products/details/:id",
{
templateUrl: "Templates/details.html",
controller: "productDetailsController"
})
.when("/products/edit/:id",
{
templateUrl: "Templates/edit.html",
controller: "productEditController"
})
// AngularJS Service
app.factory('productService', function ($http, $routeParams) {
return {
getDataById: function () {
//return promise from here
return $http.get("http://localhost:43618/api/Products", {
params: { id: $routeParams.id }
});
}
};
});
// Utilization of Service Method in AngularJS Controllers
app.controller("productDetailsController", function ($scope, $http, $routeParams, $location, productService) {
$scope.message = "Product Details";
productService.getDataById().then(function (response) {
$scope.product = response.data;
}, function (error) {
console.log("Error occurred ", error);
});
});
.controller("productEditController", function ($scope, $http, $routeParams, $location, productService) {
$scope.message = "Edit Page";
$scope.product = {};
productService.getDataById().then(function (response) {
$scope.product = response.data;
}, function (error) {
console.log("Error occurred ", error);
});
$scope.updateProduct = function (product) {
$http({
method: "PUT",
url: "http://localhost:43618/api/Products",
params: { id: $routeParams.id },
data: product
})
.success(function () {
alert("Product Updated Successfully");
$location.path('/products');
});
}
})
2. Leveraging rootScope Object
However, using the rootScope object presents an issue: It loses its state upon page refresh.
Therefore, it is recommended to prioritize AngularJS Service over rootScope for more stability.