AngularJS中使用angular-sidebarjs点击按钮侧边栏无法关闭问题求助
Hey there! I’ve run into this exact snag with angular-sidebarjs before—let’s get your sidebar closing properly when you click those menu links.
The Root Issue
By default, angular-sidebarjs doesn’t automatically close when you click internal links (like your ui-sref navigations). It only handles clicks outside the sidebar or its built-in close button. So we need to explicitly trigger the close action when your menu items are clicked.
Step 1: Fix Template Typos First
First, I spotted a couple small issues in your template that might cause other headaches:
radius.namewon’t display the actual value—wrap it in Angular interpolation:{{radius.name}}radius_idin yourui-srefshould probably beradius.id(since you’re looping overradiusitems)- The
ng-repeatsyntaxradius in radiusis confusing—rename the collection to something likeradiusesfor clarity.
Step 2: Add a Close Function to Your Controller
First, make sure you’ve injected the Sidebarjs service into your home.js controller. Then add a simple function to trigger the sidebar close:
// home.js controller example angular.module('yourAppName') .controller('HomeController', ['$scope', 'Sidebarjs', function($scope, Sidebarjs) { // Your existing code here... // Function to close the sidebar $scope.closeSidebar = function() { Sidebarjs.close(); }; $scope.listMenus = function() { // Your existing listMenus logic... }; }]);
Step 3: Update the Template to Call the Close Function
Modify your ng-click to run both your existing listMenus() function and the new closeSidebar() function:
<sidebarjs> <div class="sidebar-head">Find User</div> <nav> <ul class="sidebar-menu"> <li ng-repeat="radius in radiuses"> <a href="#" ng-click="listMenus(); closeSidebar()" ui-sref="users({radius_id: radius.id})" ui-sref-opts="{reload: true}"> {{radius.name}} </a> </li> </ul> </nav> </sidebarjs>
Alternative: Auto-Close on Route Change
If you want the sidebar to close anytime the route changes (not just when clicking these menu items), listen for UI-Router state transitions and trigger the close action automatically:
angular.module('yourAppName') .controller('HomeController', ['$scope', 'Sidebarjs', '$transitions', function($scope, Sidebarjs, $transitions) { // Close sidebar whenever the route changes $transitions.onSuccess({}, function() { Sidebarjs.close(); }); // Your existing controller code... }]);
This way, no matter how the user navigates away (even via the browser back button), the sidebar will close automatically.
内容的提问来源于stack exchange,提问作者Vicky

