Search code examples
angularjsangularjs-scopesteroidsrootscope

How to change the AngularJS scope in a different HTML page?


I hope someone can help me with this problem, it really drives me crazy :P I have created a Plunker in order to illustrate the problem. See the Demo here http://plnkr.co/edit/BRlDgKYlE87Bh3t53tpZ?p=preview.

 My code is in the plunker.

So my problem is that I'm not able to change my scope value in a different html view that I'm in. As the Plunker show, I have two buttons in index.html; button1 and button2. When I click on button1 I want scope.test to change to "button1", and when I click on button2 it should change to "button2", this value exists in index2.html. As you can see on the console.log message, that never happen. I use rootscope, but still I'm only able to change the value if the scope exists in the same html page and not in another. Please help!


Solution

  • What you have coded up is not a single page application, html2 has no idea about your angular code in app.js. You need to use routing and you should be using a service to share state between the two 'pages' or views in the case of angular routing

    EDIT

    Take a look at this plunkr

    Here you will see angular routing in action and a service that can be shared between the two controllers. When switching between the two pages, the controllers they are attached to get destroyed, so going from Page 1 to Page 2 means that contollerA no longer exists, so you need to use the service to store the state of what was clicked on from Page 1.

    Hope this makes sense!