Search code examples
angularjsangular-ui-routerangularjs-rootscope

Show and hide using $rootscope


I have a search bar in my index.html template that I need to hide on some pages. I am using ui-router and $state.

The only way I can make this work is to inject $rootscope into all my controllers to either ng-hide: true or false to turn them on or off where needed. (I only really need to hide on 1 or 2 pages)

I don't think this is the correct way to do it as all my controllers are now dependent and injected on the $rootscope.

Is there another way to do this?


Solution

  • Let's start with a global controller example GlobalCtrl which is added to the body or html tag like ng-controller="GlobalCtrl.

    Doing this will enable us to keep the scope of this GlobalCtrl throughout your single page Angular app (as you are using ui-router) and we can avoid the usage of $rootScope (actually mimicking the usage of $rootScope).

    Now, inside your GlobalCtrl define something like this:

    // Using an object to avoid the scope inheritance problem of Angular
    // https://github.com/angular/angular.js/wiki/Understanding-Scopes
    $scope.globalData = {showSearchBar: true};
    
    // This callback will be called everytime you change a page using ui-router state
    $scope.$on('$stateChangeStart', function(event, toState, toParams) {
        $scope.globalData.showSearchBar = true;
    
        // Just check for your page where you do not want to display the search bar
        // I'm using just an example like I don't want to display in contac-us page named state
        if (toState.name == 'contact-us' || toParams.foo == "bar") {
            $scope.globalData.showSearchBar = false;
        }
    });
    

    Now, in your index.html, just use ng-show:

    <div ng-show="globalData.showSearchBar">
        <input type="text" ng-model="query" />
    </div>