Sunday, November 1, 2015

Using Bootstrap navbar in AngularJS without adding bootstrap scripts

I wanted to create a web app in AngularJS that uses Bootstrap navbar styles as its navigation menu without adding bootstrap scripts to the application. I like how bootstrap navbar looks:



Here is how I did it:

  • Instead of downloading the whole bootstrap bundle from their web site, I downloaded the css only. There is a bower/npm package that deploys the css files only, so I simply did: bower install bootstrap-css-only --save
  • I included the bootstrap.css file in my main html page:  <link rel="stylesheet" href="bower_components/bootstrap-css-only/css/bootstrap.css">
  • I used the navbar in the bootstrap starter code here as my starting point: https://getbootstrap.com/examples/starter-template/
  • The starter navbar code will work great with Angular (it is css after all) except for two things:
    • The auto collapse problem: Bootstrap navbar auto collapses when the screen width is lower than 768 pixels to look like below. This won't work without the bootstrap scripts, but I figured that its logic is not that complex to be implemented in angular.To fix the auto collapse in the "Angular" way, here is what I did:
      • Added the attributes below to the collapse button ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"
      • Added the attribute below to the main menu div ng-class="{collapse: isCollapsed}"
    • The drop down problem: Drop down menus in the navbar do not work without the JS. I did not attempt to fix this (maybe because I do not need drop downs in my current app), but I will try to fix it. 

No comments:

Post a Comment