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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With