You're making progress in the right direction by considering using a factory or service to share code across controllers. It's important to note that in Angular, services (and factories) are singletons, meaning they are only instantiated once when the application starts and then any reference to it in a controller refers to the same instance. Here is an example of how this can be implemented:
var myApp = angular.module('myApp', []);
myApp.service('MyService', function() {
let _someValue = 'Initial Value';
this.setValue = function(value){
_someValue = value;
}
this.getValue = function(){
return _someValue;
}
});
//First Controller Execution
myApp.controller('ControllerA', function($scope, MyService) {
MyService.getValue(); //Initial Value
MyService.setValue("NEW VALUE!");
});
//Executed after ControllerA
myApp.controller('ControllerB', function($scope, MyService) {
MyService.getValue(); //NEW VALUE!
});
In this scenario, MyService maintains the state of the variable _someValue. ControllerA has access to MyService and can update the value using its methods. Any subsequent call to retrieve this state, such as from ControllerB, will return the updated value.