更改元素高度angularJS

时间:2015-08-01 14:30:00

标签: javascript html angularjs angularjs-directive

我在下面有这个代码,我认为它会起作用。但它没有

'use strict';

angular.module('remnantApp')
  .directive('bigDiv', function ($timeout) {
    return {
      restrict: 'E',
      scope: {},
      template: '<div style="height: {{height}}, background-color: black;">Hello</div>',
      link: function(scope, element, attrs) {
        scope.height = angular.element(window).height();
      }
    };
  });

请帮忙

2 个答案:

答案 0 :(得分:3)

当您使用内联模板时,

templateUrl应为template,同时可以使用ng-style呈现动态样式,然后模板变为ng-style="{height: height + \'px\' }"

<强>标记

<big-div><big-div>

<强>代码

angular.module('remnantApp',[])
  .directive('bigDiv', function ($timeout,$window) {
    return {
      restrict: 'E',
      scope: {},
      template: '<div class="big-div" ng-style="{height: height + \'px\' }" style="background-color: black;">Hello</div>',
      link: function(scope, element, attrs) {
        scope.height = $window.innerHeight; //without jQuery
        //other alternative would be
        //element.find('.big-div').css(height, scope.height);
      }
    };
});

Working Plunkr

答案 1 :(得分:2)

在使用动态样式属性时,我会尝试使用ng-style

'use strict';

angular.module('remnantApp')
  .directive('bigDiv', function ($timeout) {
    return {
      restrict: 'E',
      scope: {},
      template: '<div ng-style="styles">Hello</div>',
      link: function(scope, element, attrs) {
        scope.styles = {
          height: angular.element(window).height(),
          'background-color': 'black'
        };
      }
    };
  });