Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use two AngularJS services with same name from different modules?

Supposed I have two modules for AngularJS, e.g. foo and bar, and both of them define a service called baz.

In my application I depend on them by saying:

var app = angular.module('app', [ 'foo', 'bar' ]); 

Then I can try to use the baz service in a controller by using

app.controller('blaController', [ '$scope', 'baz', function($scope, baz) {   // ... }]); 

How can I define which of the two services I'd like to use? Is there something such as a fully-qualified name?

like image 963
Golo Roden Avatar asked Jul 25 '13 15:07

Golo Roden


People also ask

Can we have multiple modules in AngularJS?

Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.

Can we have two ng app in AngularJS?

Only one ngApp directive can be auto-bootloaded per HTML Document but you can have multiple apps as long as you manually bootstrap the subsequent ones.

Can angular applications ng app be nested within each other?

AngularJS applications cannot be nested within each other. Do not use a directive that uses transclusion on the same element as ngApp . This includes directives such as ngIf , ngInclude and ngView .

Can we have two controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application.


1 Answers

The service locator looks services up by name (angularjs guide DI). However "Namespacing" services in AngularJS:

As of today AngularJS doesn't handle namespace collisions for services so if you've got 2 different modules with the service named the same way and you include both modules in your app, only one service will be available.

I guess you can make the fully qualified name "by hand": name the service foo.baz and bar.baz instead of plain baz. It's kind of a self-delusion. Moreover, writing it this way doesn't make namespacing real, but another person that reads the code might think so.

like image 60
Eduard Gamonal Avatar answered Sep 26 '22 04:09

Eduard Gamonal