AngularJS 1.x handles dependencies in a rather peculiar manner. However this and many other design issues are fixed and improved in Angular 2.
Now consider this example:
You would expect the display to give result of :
srvc1 from app3
srvc1 from app4

However you get:
srvc1 from app4
srvc1 from app4

JS Bin on jsbin.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html ng-app="app">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
    <script>
        angular.module('app',['app1','app2']);
 
        angular.module('app1',['app3']).controller('ctr1',function($scope,srvc1){
            $scope.name = srvc1.getName();
        });
 
        angular.module('app2',['app4']).controller('ctr2',function($scope,srvc1){
            $scope.name = srvc1.getName();
        });
 
        angular.module('app3',[]).factory('srvc1',function(){
            return{
                getName:function(){return 'srvc1 from app3';}
            };
        });
        angular.module('app4',[]).factory('srvc1',function(){
            return{
                getName:function(){return 'srvc1 from app4';}
            };
        });
    </script>
</head>
 
<body>
    <div ng-controller="ctr1">
        {{name}}
    </div>
    <div ng-controller="ctr2">
        {{name}}
    </div>
</body>
 
</html>

The reason being, all the dependencies when injected into a module goes into a single bucket where everything is identified by name. Now in the above example srvc1 from app3 and srvc1 from app4 are all put into the same bucket and the srvc1 from app3 will be overridden by srvc1 from app4. So it is always advisable to prefix your services,factories with some sensible string.

“There is always something more to learn and understand.”
-Rushi

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>