2015-02-09 174 views
9

我是新角度:-)我只是想设置一个div的尺寸到另一个,任何帮助赞赏。在angularjs中设置一个div的高度到另一个div

<div class="front"> 
    <img ng-src="{[galery.pages[0].thumbnailUrl]}" > 
</div> 
<div ng-style="galery.pages[1] ? '' : setBackDimensions(); " ></div> 

,并在控制器我已经补充说:

$scope.setBackDimensions = function() { 
     var imgHeight = $(".front").height; 
     var imgWidth = $(".front").width; 
     return { 
      'width': imgWidth + 'px'; 
      'height': imgHeight + 'px'; 
     } 
    }; 

和它返回的宽度和高度,但他们不会被

回答

24

我已经为你的问题的解决方案。首先我会向你解释我所做的以及为什么我这样做。

Angular的一个基本原则是,你应该避免在你的控制器中处理div元素之类的DOM元素,而是在指令中完成与DOM元素相关的大部分事情。

指令允许您将函数绑定到特定的dom元素。在这种情况下,你想要绑定一个函数到你的第一个div,它获取元素的高度和宽度并将它暴露给另一个元素。我在下面评论了我的代码,以说明我是如何实现这一目标的。

app.directive('master',function() { //declaration; identifier master 
    function link(scope, element, attrs) { //scope we are in, element we are bound to, attrs of that element 
     scope.$watch(function(){ //watch any changes to our element 
     scope.style = { //scope variable style, shared with our controller 
      height:element[0].offsetHeight+'px', //set the height in style to our elements height 
      width:element[0].offsetWidth+'px' //same with width 
      }; 
     }); 
    } 
     return { 
     restrict: 'AE', //describes how we can assign an element to our directive in this case like <div master></div 
     link: link // the function to link to our element 
     }; 
}); 

现在,我们的范围可变样式应该包含与我们的“主”元件的电流的宽度和高度的物体即使我们主元件的大小变化。

接下来,我们要应用这种风格到另一个元素,我们可以实现像这样:

<span master class="a">{{content}}</span> 
<div class="b" ng-style="style"></div> 

正如你所看到的跨度上面是我们在div主元素是我们的“奴隶”,这将始终具有与主人相同的宽度和高度。 ng-style="style"意味着我们将包含在我们的作用域变量scope中的css样式添加到span中。

我希望你能理解我为什么以及如何得到这个解决方案,here is a plnkr,演示了我的解决方案。

+0

感谢这么多如此详细的解答 – lesek 2015-02-10 08:09:18

+0

这是不会,如果你有更多的工作而不是页面上的其中一个 – 2017-10-28 03:34:21

0

下面是将其他元素宽度应用于当前元素的示例。

宽度有类名称的元素的“容器”将适用于使用flexibleCss角JS指令

到div的
<div flexible-width widthof="container"> 
</div> 

myApp.directive('flexibleWidth', function(){ 

    return function(scope, element, attr) { 
      var className = attr.widthof; 
      var classWidth = angular.element(document.querySelectorAll('.'+className)[0])[0].clientWidth; 
      element.css({ 
       width: classWidth+ 'px' 
      }); 
      }; 
    }); 
相关问题