Sharing data between two controllers with $rootScope

2013-10-04
NodeJS/ UI Testing

So I had a situation where I needed to share a flag between controllers in Angular JS and the documentation was a bit lacking around $rootScope. Basically using a link in one controller I wanted to be able to toggle a container within another controller into view with a CSS3 transition. Using the ngClick directive I wanted to toggle the class on the container (ngClass) but setting/reading $rootScope directly in the controllers didn’t yield much joy.

What I tried is below…
`


<div data-ng-controller=”homeController”>

<a href data-ng-click=”showSettings = !showSettings”>Settings</a>

</div>

<div data-ng-controller=”settingsController”>
<div id=”settings” data-ng-class=”{‘active’: showSettings}”>…</div>
</div>

app.controller(‘homeController’, function($scope, $rootScope) {
$rootScope.showSettings = false;
});

app.controller(‘settingsController’, function($scope, $rootScope) {
$rootScope.showSettings;
});
`

This failed miserably so in the end what worked was more a case of using functions within each controller to set and read a $rootScope flag. It still feels a bit dirty (like using the viewbag in ASP MVC) but I don’t feel like a service is right for just data unless in encapsulates some of the other parts of the code (like returning the class). My exciting journey of discovering Angular JS continues. I’ll be looking into a better way to do this sort of thing.

`


<div data-ng-controller=”homeController”>

<a href data-ng-click=”toggleSettings()”>Settings</a>

</div>

<div data-ng-controller=”settingsController”>
<div id=”settings” data-ng-class=”getSettingsClass()”>…</div>
</div>

app.controller(‘homeController’, function($scope, $rootScope) {
$scope.toggleSettings = function() {
if($rootScope.showSettings) {
$rootScope.showSettings = !$rootScope.showSettings;
} else {
$rootScope.showSettings = true;
}
};
});

app.controller(‘settingsController’, function($scope, $rootScope) {
$scope.getSettingsClass = function() {
return $rootScope.showSettings == true ?
“active” : “”;
}
});
`


Comments: