How to instantiate a service dynamically?

I have a service Utilsthat is very difficult. I want to use some functions defined in it for a specific user action. Since this service is heavy, I want to create it lazily (with user action).

How do I achieve this?

Service

module.service('Utils', function (dep1, dep2) {
   this.method1 = function () {
      // do something
   }
   // other methods
});

controller

module.controller('AppCtrl', function ($scope) {
    // I don't want to inject Utils as a dependency.

    $scope.processUserAction = function () {
       // If the service is not instantiated 
       // instantiate it and trigger the methods defined in it. 
    }
});

Markup

<div data-ng-controller="AppCtrl">
    <button data-ng-click="processUserAction()"> Click Me </button>
</div>
+1
source share
1 answer

You can use the $ injector service to get services anywhere: https://docs.angularjs.org/api/auto/service/$injector . Add $ injector to your controller and whenever you need the service:

, $injector, .

 angular.module('yp.admin')

    .config(['$stateProvider', '$urlRouterProvider', 'accessLevels', '$translateWtiPartialLoaderProvider',
        function ($stateProvider, $urlRouterProvider, accessLevels, $translateWtiPartialLoaderProvider) {
            $stateProvider
                .state('admin.home', {
                    url: "/home",
                    access: accessLevels.admin,
                    views: {
                        content: {
                            templateUrl: 'admin/home/home.html',
                            controller: 'AdminHomeController'
                        }
                    }
                });
        }])
    .service('UtilsService', function() {
        console.log('utilsSerivce instantiated');
        return {
            call: function() {
                console.log('Util.call called');
            }
        };
    })

    .controller('AdminHomeController', ['$scope', '$rootScope', 'UserService', '$injector',
        function($scope, $rootScope, UserService, $injector) {
        $injector.get('UtilsService').call();
    }]);    

:

stateChangeStart from:  to: admin.home
stateChangeSuccess from:  to: admin.home
utilsSerivce instantiated
Util.call called

JS, ocLazyLoad : https://github.com/ocombe/ocLazyLoad. , .

+1

All Articles