Reputation: 803
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?
Upvotes: 4
Views: 37387
Reputation: 64903
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>
Upvotes: 2
Reputation: 3195
Most of the situation we need to hide and show the UI component. In angular js its pretty easy.
Use ng-hide = true -- is the directive, it check the boolean
<div ng-app="" ng-controller="MyController">
<div >
<button name="click" ng-click="click()">Show Donet Chart</button>
</div>
<div class="bg-primary" ng-hide="titleEnabled">
<span class="glyphicon glyphicon-stats"></span>Title
</div>
<div ng-hide="divEnabled">
------------
</div>
</div>
And this is the controller
function myController($scope){
$scope.titleEnabled = true;
$scope.divEnabled = true;
$scope.click = function(){
$scope.titleEnabled = false;
$scope.divEnabled = false;
}
}
Upvotes: 1
Reputation: 943
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.
Upvotes: 5