I would like to dynamically inject some dependencies within a controller. I can do it easily with the $injector like this:
var app = angular.module('app', []);
app.service('serv1', function() {
var me = this;
this.welcome = function(str) {
console.log("Welcome " + str + "!");
};
});
app.controller('Ctrl', function($scope, $injector) {
var servMe = $injector.get('serv1');
$scope.greeting = function() {
servMe.welcome('Master Obi-wan');
};
});
But, let's say that I have a huge service serv1 and do not want to 'bloat' my page if not required. I would like to do it from within my controller (Plunker provided: http://plnkr.co/edit/Szs4Pg?p=preview)
The error I am facing is that the $injector does not seem to know about the newly loaded service. Should I refresh its cache or something? Should I instantiate a new one?
Many thanks in advance.
script.js
var app =angular.module('app', ['oc.lazyLoad']);
app.controller('Ctrl', function($scope, $injector,$ocLazyLoad) {
// But not from inside the controller
$ocLazyLoad.load('serv1.js').then(function(){
var servMe = $injector.get('serv1');
$scope.greeting = function() {
servMe.welcome('Master Obi-wan');
};
});
});
serv1.js
angular.module('app',[]).service('serv1', function() {
this.welcome = function(str) {
console.log("Welcome " + str + "!");
};
});
HTML
<html>
<head>
<link data-require="[email protected]" data-semver="1.5.3" rel="stylesheet" href="Bootstrap" />
<script data-require="[email protected]" data-semver="1.5.3" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/oclazyload/1.0.9/ocLazyLoad.min.js" ></script>
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="Ctrl">
<button ng-click="greeting()">Click me!</button>
</div>
</body>
</html>
This code worked for me:
app.controller('Ctrl', function($scope, $injector) {
$injector.invoke(["ServiceName", function(service){
$scope.service = service;
}]);
}
The literal string could be any variable provided dynamically. Source here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With