Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs: Does same controller at different pages share scope?

Tags:

angularjs

I am new to learning Angularjs and kinda confused. I want to ask that if the same controller is binded at different pages does those pages share the same scope variable or they have their own isolated scope? Remember both of the pages are using the same controller.

like image 753
Eesa Avatar asked Mar 15 '23 00:03

Eesa


1 Answers

From the documentation:

When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope.

So 1) it is not the same controller, those are two instances of the same constructor functions (a.k.a class) and 2) new scope is created as a child of a scope controller is attached to.

Another point from documentation:

Scopes are arranged in hierarchical structure which mimic the DOM structure of the application.

So two separate DOM elements cannot have same scope - it would heavily affect Angular structure. Each controller can only get an access to the scope of element it is attached to.

If you suffering because of one scope being updated when another one is changed, please post your code as you can have "surprise closure" in your controller definition.

like image 67
BroiSatse Avatar answered Mar 25 '23 10:03

BroiSatse