2

I am using the same controller in several HTML pages in my project. My problem is that each page links to the other and instead of them all using the same exact controller they duplicate it each time the next page is opened and each page is using its own controller, which means, all the data saved in the previous controller will not apply on the next page with the new duplicated controller.

I recently acknowledged that each controller has its own ID ($scope.$id), so:

  • Is there an option for me to request a specific controller to be used on the HTML page based on its controller ID?

  • Or is there an alternate option to store the variables of the controller in another place where i could use them without being concerned that they will reset on each page?

Mistalis
  • 17,793
  • 13
  • 73
  • 97
shay.k
  • 503
  • 1
  • 7
  • 15
  • 3
    There are severals ways (services?) to pass data from a controller to an another one. – Mistalis Nov 15 '16 at 08:48
  • 1
    you can use `ng-switch-view` to switch views and then swap the html pages which uses same controller.. In the way your parent page will contain the controller and rest of all html pages will get changed depending on condition ...and the controller remain same for all pages ... that was on parent page. – Atul Sharma Nov 15 '16 at 08:49
  • 1
    There are other ways the most suited one will be Angular Service to store data and retrieve them as when required – Manish Nov 15 '16 at 08:49
  • 1
    @atulquest93 i think you didn't read the complete question. He has written ---Or is there an alternate option to store the variables of the controller in another place where i could use them without being concerned that they will reset on each page?-- this seems to be hi main concern and the issue he is facinng is that whenever a new view is loaded the controller is again initialized so earlier state is not available and he is not able to use that data. – Manish Nov 15 '16 at 08:54

1 Answers1

0
<div ng-controller="myCtrl">
            <div ng-switch on="condition">
                <div ng-switch-when="condition_output_1">
                   <div ng-include="'html_page_1_url.html'"></div>
                </div>
                <div ng-switch-when="condition_output_2">
                     <div ng-include="'html_page_1_url_2.html'"></div>
                </div>
            </div>
    </div>

Now, Swap html_page_1_url.html and html_page_2_url.html or any html

myCtrl this will remian same for all.


To transfer data between controllers.. You can use

  • $rootscope
  • services
  • localstorage
Atul Sharma
  • 9,397
  • 10
  • 38
  • 65
  • Thanks, i am currently using `$rootScope` and i wanted to avoid this. i will surely look at the other options! – shay.k Nov 15 '16 at 09:06