Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ng-show with a controller

Tags:

angularjs

I have written an HTML file which consists of a sidebar and a main container which is mapped to a partial. Now, when the partial is loaded based on the config route, I want the sidebar to hide from the browser. For this I tried using ng-show on the sidebar div.

Is it the right approach to hide the div from the controller when the routes matches? If so, how do I bind the ng-show to the controller?

like image 895
Pradeep Avatar asked Feb 13 '23 09:02

Pradeep


2 Answers

What I usually do is a structure like this:

<nav ng-show="sidebar.show" id="sidebar" ng-controller="sidebarController">
    [...]
</nav>
<div ng-view>
</div>

So, the sidebar has his own controller (and it's own scope); then inside the partial's controller you can think about changing the value of sidebar.show. For example:

// sidebarController
function sidebarController($rootScope, $scope){
  $rootScope.sidebar = {
    show  : true;
  };
  $scope.sidebar = $rootScope.sidebar;
}

// partialController
app.controller("partialController", function($rootScope, $scope) {
  $rootScope.sidebar.show = false;
});

But that's just one way to do it.

PS: ng-show just hide the element, but it will still be in the DOM; I usually prefer ng-if as it doesn't add the element to the DOM.

like image 104
Polmonite Avatar answered Mar 05 '23 00:03

Polmonite


I would create a controller for your sidebar and inject in $scope and $location

function sideBarCtrl($scope, $location){}

Then I would listen for $routeChangeSuccess on the $scope and based upon the new path, you can determine whether to show/hide your sidebar based upon the path defined on $location

$scope.show = true; // or false
$scope.$on('$routeChangeSuccess', function(){
    // logic here to show/hide based upon $location.path()
    var path = $location.path();
    if (path === 'somePathToShow'){
        $scope.show = true;
    } else if (path === 'somePathToHide') {
        $scope.show = false;
    }
});

And per request, your markup would look something like this.

<body>
    <div ng-controller="SideBarCtrl" ng-show="show">
        <!-- sidebar content -->
    </div>
    <div ng-view></div>
</body>
like image 22
Brocco Avatar answered Mar 05 '23 01:03

Brocco