3

I am trying to set the height of a div based on its width, and then applying a multiplication factor. I am using angularjs in my code, and I need to use the class to base the directive on.

my html is as follows:

<div ng-class="(box.banner) ? 'bannerbox col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xl-4' : 'cardbox col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xl-4'"  ng-repeat="box in boxes">

If the div is a bannerbox (ie has the bannerbox class) then I need the height of this div to be 1.08571 * the width. I understand I need to do this using a directive, but not sure where I am going wrong. My directive code is as follows:

app.directive('bannerbox', function () {
return {
    restrict: "C",
    link: function (scope, element) {
        element.height(element.width * 1.08571);
    }
}

});

Any help would be much appreciated!

8
  • What is your error/problem? What happens with your directive? Commented Mar 17, 2014 at 16:30
  • 1
    sorry I forgot to add. The height is not altered from its natural state, so I do not thing the directive is working. I wondered if this was because this code is dynamically loaded using ng-view. Commented Mar 17, 2014 at 16:34
  • also, the class is set correctly using ng-class so this is not the problem. Commented Mar 17, 2014 at 16:40
  • Did you try my solution ? Is it working for you ? Commented Mar 17, 2014 at 17:01
  • Hi Timothee - I can see it working in the fiddle, but I cannot get it to work with my code. I cannot understand why but I do not think the directive is triggered although it is definately loaded. Commented Mar 17, 2014 at 17:32

1 Answer 1

3

You need to watch for the width of the element because the width's value is zero initially.

When the link function is called, the width of the element is zero.

Assuming you're using angularJs and jQuery:

app.directive('bannerbox', function () {
    return {
        restrict: "A",
        link: function (scope, element) {
            scope.getWidth = function () {
                return $(element).width();
            };
            scope.$watch(scope.getWidth, function (width) {
                // Do your work with the element width.
                // Be careful not to change the width of the element or you will create an infinite loop.
                // Set the height of the element.
            });
        }
   }
});

Working JsFiddle example here : http://jsfiddle.net/ZtQ2p/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.