set height of one div to another div in angularjs

后端 未结 2 1607
清酒与你
清酒与你 2020-12-16 19:27

i am new to angular :-) i simply want to set dimensions of one div to another, any help appreciated.

 
2条回答
  •  有刺的猬
    2020-12-16 19:35

    I have created a solution for your problem. First I will explain to you what I have done and why I did it this way.

    One basic guideline in Angular is, that you should avoid dealing with DOM elements like divs in your controllers and instead do most things related to DOM elements in directives.

    Directives allow you to bind functions to specific dom elements. In this case you want to bind a function to your first div, that gets the height and width of your element and exposes it to another element. I have commented my code below to show how I achieved this.

    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 

    Now our scope variable style should contain an object with the current width and height of our "master" element even if the size of our master element changes.

    Next up we want to apply this style to another element which we can achieve like so:

     {{content}}
     

    As you can see the span above is our master element in the div is our "slave", which will always have the same width and height as it's master. ng-style="style" means that we add the css style contained in our scope variable called style to the span.

    I hope you understand why and how I got to this solution, here is a plnkr with a demo displaying my solution in action.

提交回复
热议问题