Search code examples
cssangularjsionic-frameworktoggleng-class

How to make the toggle and the button change if any one of it had changes in different HTML


I'm using sidemenu template.

I have toggle (true= online, false= offline) in the left menu, while the button (true= online, false= offline) in the other html.

What I'm trying to do is, if the user turn on the toggle 'leftMenu.html', it will be true, then the button in 'page1.html' also change into true.

Here is my code for toggle in my left menu (leftMenu.html)

<span ng-controller="toggleCtrl">
   <p ng-bind=toggleColor></p> 
     <ion-toggle  ng-checked=toggleColor ng-click="one()" toggle-class="toggle-calm">
        Airplane Mode 
     </ion-toggle>
</span>

Here is my code for button in the other .html (page1.html)

<button class="btn btn-default"  ng-click="one()" ng-class="{'on': toggleColor, 'of': !toggleColor}">on</button>

<button class="btn btn-default" ng-click="one()" ng-class="{'on': !toggleColor, 'of': toggleColor}" >off</button>

Here is my js (app.js). Both HTML used the same controller 'toggleCtrl'

  .controller('toggleCtrl', function($scope) {
    $scope.toggleColor = true;

    $scope.one = function(){
      $scope.toggleColor = !$scope.toggleColor;
    }
 }) 

Already implement ng-bind, but it didn't worked in other HTML. It only worked in the same HTML.

Here is my codePen http://codepen.io/aishahismail/pen/pgPEoJ


Solution

  • According to your scenario use $rootScope instead of $scope variable and issue will be solved.

    Just change your controller to the following and issue will be solved I have checked the same in your code pen.

    .controller('toggleCtrl', function($scope,$rootScope) {
        $rootScope.toggleColor = true;
        $scope.one = function(){
            $rootScope.toggleColor = !$rootScope.toggleColor;
        }
    });
    

    Hope issue is resolved.