Can two pages share a controller during routing, such as
javascript
.state('a', { ... controller : 'aaaController' }) .state('b', { ... controller : 'aaaController' })
If yes, is the controller an independent scope or a public one? For example, if I declare a variable i
in the controller and change the value of i
in page a, when I route to b When the page is opened, will the value of i
change accordingly?
I am also learning angularjs recently. Regarding the problem mentioned by the poster, I can make a simple demonstration:
It has the following html structure, different views, and the same controller
Part of the controller code:
First click the show button, the output result is as follows:
Then click the change to 3 button and click the show button again. The result is as follows:
It can be seen from this experiment that although it is the same controller, the scopes are actually two completely unrelated scopes.
The scope structure is also tree-shaped, corresponding to the dom structure. The above html structure will have two scopes.
Let’s look at another obvious example:
Look at the console
The result is printed twice, indicating that the method was executed twice. If the scope is shared, it will not be executed twice.
In summary: You declare a variable i in the controller, and change the value of i in page a. When you route to page b, the value of i will not change
hope to help you!
It’s weird to use it this way, I’m not sure if it’s feasible to use it this way
Personally I think the normal usage is:
One page, one controller
If you need to share variables and methods between controllers, you can build a service in angular to store the variables and methods. In different controllers, just inject the service we wrote
The official document also clearly states that service is used to share code:
Services
Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.
https://docs.angularjs.org/guide/services
After switching the route, the life cycle of the controller is over, and the current
$scope
and sub-scopes are dead.If you need to share data between multiple controllers, you can use services.