AngularJS set css to tag in directive (Bootstrap sticky footer)

时间:2017-06-09 12:58:15

标签: html css angularjs angular-ui-bootstrap

I am developing my first AngularJS app using Bootstrap as the responsive framework. The app needs an bs sticky footer. Normally i use jQuery to calculate the outerHeight of the footer and set the value to the body tag as padding bottom in css.

I don't want to use jQuery so i've been fiddling to make this work in pure AngularJS.

HTML

  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name=viewport content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=0">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/style.min.css" rel="stylesheet" type="text/css" media="all" />
  </head>

  <body ng-app="ngApp">
    <header>
    </header>
    <main>
      <div class="container">
        <div class="content-wrapper">
          <div class="row">
            <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
              <!--  -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
              <!--  -->
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer footer-height>
      <div class="container">
        <div class="content-wrapper">
          <div class="row">
            <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
              <!--  -->
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
              <!--  -->
            </div>
          </div>
        </div>
      </div>
    </footer>
    <!-- Scripts  -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap.min.js"></script>
    <!-- App -->
    <script src="app/app.js" type="text/javascript"></script>
  </body>
</html>

JS

var app = angular.module("ngApp", [])
  // footer height
  .directive('footerHeight', function() {
    return {
      link: function(scope, element) {
        scope.$watch(function() {
          var footerHeight = element[0].offsetHeight;              
          var elBody = angular.element(document).find('body')
          elBody.css('padding-bottom', footerHeight);
          console.log(footerHeight);
        });
      }
    };
  }); // end app

The height of the footer is calculated correctly as seen in the console but the value is not being set to the body tag.

1 个答案:

答案 0 :(得分:0)

我认为您需要创建自己的指令,然后才能使用div

app.directive('outerHeight', function(){
  return{
    restrict:'A',
    link: function(scope, element){
       return angular.element(element).prop('offsetHeight');
    }
  };
});

<div  outer-height></div>