在angularjs中设置内联样式

问题描述 投票:1回答:1

我正面临一个问题,试图在他的孩子被渲染后在元素上设置一个css属性。实际上,我需要将父元素的高度设置为等于其第一个子元素的高度。问题是他的孩子在ng repeat指令中呈现,所以我不知道何时会计算元素高度。

首先,我尝试使用ng样式指令。它可以工作,但我只需要设置一次css,而不是每次范围都改变,因为我的公式是这样的:parentheight = firstChildHeight * scopeValue和scopeValue将在执行时间内改变。

非常感谢您的帮助!

angularjs directive
1个回答
2
投票

对于第一部分,您可以设置一个监视第一个孩子的计算高度的手表。这最好在这样的指令中完成:

app.controller('MainCtrl',function($ scope){$ scope.myMultiplier = 2;});

app.directive('firstChildHeight', function(){
  return {
    link: function(scope, element, attrs){

     function firstChildHeight(){
         return element.find(':first-child').height();
     }

     //This will only get evaluated one time
     var multiplier = scope.$eval(attrs.heightMultiplier);

     scope.$watch(firstChildHeight, function(height){
        element.css('height', height*multiplier);   
     });
    }
  }
});

请注意我是如何从范围中读取乘数的一次(我没有设置监视以使乘数变量保持最新)。这应该在最初设置后保持乘数变化(我理解的是你想要的)。

你可以像这样使用它:

app.controller('MainCtrl', function($scope) {
  $scope.myMultiplier = 2;
});

然后:

  <body ng-controller="MainCtrl">
    <div first-child-height height-multiplier="myMultiplier" style="background: red;">
      <div>You should see me in red</div>
      <div>I am in red too because height multiplier is 2</div>
      <div>I don't have red</div>
    </div>
  </body>

正如你所看到的,你真的不需要弄清楚ng-repeat何时完成渲染,父亲的高度总是与第一个孩子的高度相乘,再乘以乘数的值。编写指令的时间。

这是一个玩家的傻瓜:

http://plnkr.co/edit/DqmcKgq00jdwjs5IZh7H?p=preview

我是否正确理解您的要求?

© www.soinside.com 2019 - 2024. All rights reserved.