How to use Angular $scope.variable from controller 1 in ng-class of div using controller 2

245 Views Asked by At

I have 2 controllers boxController.js and homeController.js. On box.html page I initialize the boxController.js. Now, I need to use ng-class on box.html page but the variable I need to use inside ng-class is in homeController.js

I have tried service and factories but these return variables that can be shared across multiple controllers. I am somehow confused about using a shared variable inside html, not inside the controller.

**** homeController.js ****

$scope.defaultState = false;
$scope.submitNow = false;

$scope.default = function () {
    $scope.defaultState = !$scope.defaultState
}

$scope.defaultToggle = function () {
    $scope.submitNow = !$scope.submitNow
}

**** box.html (This page uses boxController.js, not homeController.js) ****


// I need to use $scope.submitNow and $scope.defaultState variables in the ng-class of this div

<div ng-controller="boxController" class="ui" ng-class="{'two.column.grid' : submitNow, 'one.column.grid' : defaultState}">
</div>
2

There are 2 best solutions below

0
ChickenSoups On

You have some ways to do that

  1. use $rootScope
  2. use $watch
  3. create a shared context using factory
5
Jazib On

Just adding to @ChickenSoups' answer you can also use $on and $broadcast. you would do this in the homeController.js

$scope.defaultState = false;
$scope.submitNow = false;


$scope.default = function () {
    $scope.defaultState = !$scope.defaultState;
   $rootScope.$broadcast('some-event', { defaultState: $scope.defaultState, submitNow:  $scope.submitNow});
}

$scope.defaultToggle = function () {
    $scope.submitNow = !$scope.submitNow;
    $rootScope.$broadcast('some-event', { defaultState: $scope.defaultState, submitNow:  $scope.submitNow});

}

and in your boxController.js you can catch this event like the following:

$scope.$on('some-event', function(event, args) {

    $scope.defaultState = args.defaultState;
    $scope.submitNow = args.submitNow;

});