Alan2
Alan2

Reputation: 24572

Where is a good place for me to declare / initialize $scope variables for my module?

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

Answers (1)

Maxim Shoustin
Maxim Shoustin

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

Related Questions