angularjs - How to instantiate a service dynamically? -
i have utils
service heavy. want use of functions defined in on particular user action. service heavy want instantiate lazily(on user action).
how achieve this?
service
module.service('utils', function (dep1, dep2) { this.method1 = function () { // } // other methods });
controller
module.controller('appctrl', function ($scope) { // don't want inject utils dependency. $scope.processuseraction = function () { // if service not instantiated // instantiate , trigger methods defined in it. } });
markup
<div data-ng-controller="appctrl"> <button data-ng-click="processuseraction()"> click me </button> </div>
you can use $injector service services anywhere: https://docs.angularjs.org/api/auto/service/$injector. inject $injector controller, , whenever need service use:
this worked fine me, service instantiated on $injector call, no error thrown.
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(); }]);
console gives me this:
statechangestart from: to: admin.home statechangesuccess from: to: admin.home utilsserivce instantiated util.call called
if want delay loading js should have @ oclazyload module: https://github.com/ocombe/oclazyload. addresses sorts of lazy loading use cases , yours sounds fit it.
Comments
Post a Comment