Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to $inject dynamically dependence in a controller
    text
    copied!<p>I'm still a debutant on Angularjs. I want to inject dynamically a dependency of a service (that I created) in my controller.</p> <p>But when I code a service with dependencies, I got this error :</p> <p><em>Error: Unknown provider: $windowProvider &lt;- $window &lt;- base64</em></p> <p>This is the code of the controller.</p> <pre><code>var base64 = angular.injector(['servicesModule']).get('base64'); console.log("base64", base64.encode("my text will be encoded")); </code></pre> <p>This code works:</p> <pre><code>var servicesModule = angular.module('servicesModule', []); servicesModule.factory('base64', function() { return { name: 'base64', readonly: false, encode: function(input) { return window.btoa(input); }, decode: function(input) { return window.atob(input); } }; }); </code></pre> <p>This code doesn't work :</p> <pre><code>var extModule = angular.module('ext', []); extModule.factory('base64', ['$window', function($window) { return { name: 'base64', readonly: false, encode: function(input) { return $window.btoa(input); }, decode: function(input) { return $window.atob(input); } }; }]); </code></pre> <p>Another problem is when the service is in the same module as the controller. If the module has dependencies, I doesn't work (I have $routeProvider dependence in my module config) :</p> <p><em>Error: Unknown provider: $routeProvider from mainModule</em></p> <pre><code>var mainModule = angular.module('main', [], function($routeProvider, $locationProvider) { //Some routing code } ); </code></pre> <p><strong>JS Fiddles</strong></p> <p>Same module with dependencies(controller + service) : <a href="http://jsfiddle.net/yrezgui/YedT2/" rel="noreferrer">http://jsfiddle.net/yrezgui/YedT2/</a></p> <p>Different module with dependencies : <a href="http://jsfiddle.net/yrezgui/YedT2/4/" rel="noreferrer">http://jsfiddle.net/yrezgui/YedT2/4/</a></p> <p>Different module without dependencies : <a href="http://jsfiddle.net/yrezgui/YedT2/5/" rel="noreferrer">http://jsfiddle.net/yrezgui/YedT2/5/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload