Twitter Bootstrap Navbar with AngularJS - Collapse Not Functioning

后端 未结 8 1054
夕颜
夕颜 2020-12-02 05:33

I am using Angular and Twitter Bootstrap navbar and trying to get the collapse functionality to work.

Partial: program.html

相关标签:
8条回答
  • 2020-12-02 06:20

    I wanted to get it to work with pure AngularJS and no further JavaScript library and it turned out to be quite simple. There are only two changes needed starting with the example here (bootstrap v3):

    Instead of

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
    

    I used:

    <button type="button" class="navbar-toggle" ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed">
    

    and instead of

    <div class="collapse navbar-collapse">
    

    I used:

    <div class="navbar-collapse" ng-class="{collapse: isCollapsed}">
    

    Dropdowns

    Also, if you have any dropdown menus in your navbar, the same applies to them, except the css class is not 'collapse', but 'open':

    <li class="dropdown" ng-class="{ open : dd1 }" ng-init="dd1 = false" ng-click="dd1 = !dd1">
    

    Note that multiple dropdowns will all need their own state variable on the angular root scope (if you are not using a controller). Therefore I named the first dropdown 'dd1' here, they need to be unique, otherwise multiple dropdown will open/close at the same time. (which is pretty funny, but rarely usable).

    0 讨论(0)
  • 2020-12-02 06:22

    If you are looking for Angular2. Then blow is the changes required.

    <button type="button" class="navbar-toggle collapsed" (click)="toggleCollapse()"
            aria-expanded="false">
    

    and menu should look like this.

    <div class="navbar-collapse" id="bs-navbar-collapse" [class.collapse]="isCollapsed">
          <ul class="nav navbar-nav">
            <li>
              <a href="">
                Dashboard
    

    Your controller should be be something like this.

    import { Component} from '@angular/core';
    
    @Component({
      selector: 'app-navbar',
      templateUrl: './navbar.component.html',
      styleUrls: ['./navbar.component.css']
    })
    export class NavbarComponent {
      isCollapsed: boolean = true;
    
      toggleCollapse(): void {
        this.isCollapsed = !this.isCollapsed;
      }
    
    }
    

    See, this is relatively easy in angular2. thanks to @yankee for the answer.

    0 讨论(0)
提交回复
热议问题