Prometheus
Prometheus

Reputation: 33625

Angular how to set a model inside a factory service for use in a controller?

Is it possible (and a good idea) to set a model (scope vars) in a factory service?

For example, I have a factory which defines a model below how can I now init this in the controller?

(function () {
    'use strict';
    angular.module('services.auth', [])

        .factory('AuthorisationService', function ($rootScope, $http) {

            // Public variables
            var authService = {
                user: {
                    email: '',
                    password: ''
                }

            };

            return authService;

        });


})();

controller:

.controller('LoginCtrl', ['$scope', 'AuthorisationService', function ($scope, AuthorisationService) {

     AuthorisationService();



            };


        }]);

Upvotes: 0

Views: 633

Answers (3)

sundar
sundar

Reputation: 408

If u want to share data between ur controllers u can use tat.otherwise if the data does not required for any other controllers better declare variables(public/privately) inside controller itself.

Upvotes: 0

RiesvGeffen
RiesvGeffen

Reputation: 1589

Sure you can do it that way, I love to use a service and keep the controller clean.

Take a look at this demo:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, AuthorisationService) {
  $scope.authService = AuthorisationService.authService;
});

app.factory('AuthorisationService', function($rootScope, $http) {
  var AuthorisationService = {};

  // Public variables
  var _authService = {
    user: {
      email: '[email protected]',
      password: 'test123'
    }
  };

  AuthorisationService.authService = _authService;
  return AuthorisationService;
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script data-require="[email protected]" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Email: {{authService.user.email}}</p>
  <p>Password: {{authService.user.password}}</p>
</body>

</html>


If you have any more questions about this just let me know!

Upvotes: 1

Patrick Kelleter
Patrick Kelleter

Reputation: 2771

You can pass the scope of the controller to the factory as a parameter and then set values on that scope. The answer to the question if this is a good idea: rather not. It usually isn't best practice to do so. Better change your variables of your scope in your controller only and if you needs variables in your service then those variables should be set there and be used from the controller via getters/setters.

Upvotes: 1

Related Questions