简体   繁体   中英

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();



            };


        }]);

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.

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: 'test@gmail.com', password: 'test123' } }; AuthorisationService.authService = _authService; return AuthorisationService; }); 
 <!DOCTYPE html> <html ng-app="app"> <head> <script data-require="angular.js@1.4.x" 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!

如果要在我们的控制器之间共享数据,则可以使用tat。否则,如果不需要其他任何控制器使用该数据,则最好在控制器本身内部声明变量(公共/私有)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM