Search code examples
javascriptangularjsangularjs-routing

AngularJS How would one run two controllers from one website, and have one of them change


The problem

I'm trying to right an AngularJS web page, and I have variables stored in a controller. This controller is bound to the first tab. I want to be able to access the variables belonging to this controller (and keep a loop running), from a second tab (with it's own controller). When I change tabs, it loses focus of the first controller, and resets the variables when I swap back onto it.

Possible Fix?

Having a main controller running across all tabs, and have that run the loop and store all the important variables. Then have the individual tab's controller just access the methods/variables from this controller.


Solution

  • First what is interesting is why you are using loops for update variables? use $watch()

    In general there are couple ways to share variables across angular application.

    1. You can use nested controllers and share variables in parent controller. You will have $scope.$parent.variable but angular will do this for you and you can just call it by $scope.variable. Than all child controllers will share its parents variables. see angular ui router nesting
    2. Have service to store shared variable. In this case you will need to have some way to update service variable every time something changes in any controller. For this you can use $scope.$watch() method and for every property change update your model in service.

    Personally I prefer first approach just because binding is done in angular and save you some code you will need for service approach.

    Reason why one controller's "loop" stops is probably because of $digest cycle of your controller is not running. see more to understand how $digest cycle actually works