Reputation: 24572
I have the following:
angular.module('admin')
.controller('AdminContentController',
['$scope', '$resource', 'gridService', 'gridSelectService', 'localStorageService', 'utilityService',
function ($scope, $resource, gridService, gridSelectService, localStorageService, utilityService ) {
localStorageService.add('ls.adminPage', 'content');
$scope.entityType = 'Content';
gridService.gridSetup($scope);
and:
angular.module('admin')
.factory('gridService',
['$resource', '$timeout', 'gridSelectService', 'localStorageService', 'utilityService',
function ($resource, $timeout, gridSelectService, localStorageService, utilityService) {
var factory = {
gridSetup: function ($scope) {
$scope.grid = {
fetching: false,
pristine: true,
pageType: 'Edit'
}
I am initializing the scope variables in the service but I am not sure if this is the correct way to do this.
Is there a better way for me to set up $scope variables for the module in another place?
Upvotes: 0
Views: 4294
Reputation: 77904
Yes, its good practice to store variables into service.
Services are Singletons that you can inject to any controller and expose their values in a controller's scope.
However, you can't inject $scope
into services, there is nothing like a singleton $scope.
You can implement factory
by this way:
myApp.factory('gridService',
['$timeout',
function ( $timeout) {
var grid = {
fetching: false,
pristine: true,
pageType: 'Edit'
}
return {
gridSetup: function () {
return grid;
},
setGridSetup: function (newGrid) {
grid = newGrid;
}
}
}]);
And we use our factory from controller:
$scope.newGrid = gridService.gridSetup();
$scope.copyGrid = angular.copy($scope.newGrid);
$timeout(function() {
$scope.copyGrid.pageType = "Fess";
gridService.setGridSetup($scope.copyGrid);
$scope.newGrid = gridService.gridSetup();
}, 3000);
We load out model, after 3 sec we change pageType
and store it again. after next load we get modified model.
Demo Fiddle
Upvotes: 1