0

If I have the following :

<div ng-controller="mainCtrl">
    {{vm.name_from_service}}
</div>
....
<div ng-controller="mainCtrl">
    {{vm.name_from_service}}
</div>

Lets say they both pull the name_from_service value from a factory/service , is it correct to assume that the same service singleton is being used across both mainCtrl controller instances ?

Note that mainCtrl is used twice.


controller code snippet :

$scope.vm.name_from_service = someservice.getName();

Snippet #2 :

Both ng-view and the immediate div below use the same service to retrieve name_from_service, however name_from_service is only update in one place.

 <div ng-controller="mainCtrl">
         section 1
        {{vm.name_from_service}}
 </div>

 <div id="ngviewcontainer" ng-view=""></div>

Also I am not using any asynchronous ajax calls to retrieve name_from_service so angular should be aware of the changes.

I've tried using $timeout and $apply() . No dice .

I refactored and separated out unrelated logic into a separate controller and fixed the issue. Still a bit confused as to why only one of the two values were updating evening though both were supposedly pulling from the same service.

Fabii
  • 3,820
  • 14
  • 51
  • 92

3 Answers3

2

Yes it would be the same, unless some digest cycle synchronizations problems. There are situations, where you set a variable like this:

$scope.vm.name_from_service = someservice.getName();

But if you work with promises and $http calls, then sometime you have to watch changes in singletons manually using $watch. That's the situation where both controllers can have different values.

changtung
  • 1,614
  • 15
  • 19
1

Yes, that is why it is called singleton.

singleton pattern is a design pattern that restricts the instantiation of a class to one object

Also have a look at nearly the same question

Community
  • 1
  • 1
smnbbrv
  • 23,502
  • 9
  • 78
  • 109
1

You're using one controller - mainCtrl. Your controller can use multiple services. However, you cannot use different services under the same name in a controller. So yes, you're using the same service.