Rafael Gonzalez
Rafael Gonzalez

Reputation: 23

How to set height = width with angularjs directives to get a square div according to bootstrap grid system?

I've been playing a little bit with angularjs to create my own app and the following idea came to my mind:

I want to make a directive to make responsive square divs that work with bootstrap grid system.

Before going any further, I've already searched thoroughly for the past 4 hours and, tho I've found interesting approaches, none of them gave me a solution.

So i came up with the following code:

var app = angular.module('ClientsApp', []);

app.directive('wh', function(){
    return function(scope, element, attrs){
        var x = element.css[width];
        element.css({
            'width': x,
            'height': x,
            'border-radius':'1rem',
        });
    };
});

But, I can't make it work (I've been using angular for 2 days now). Intead if i do this:

var app = angular.module('ClientsApp', []);

app.directive('wh', function(){
    return function(scope, element, attrs){
        var x = element.css[width];
        element.css({
            'width': **x + 'em'**,
            'height': **x + 'em'**,
            'border-radius':'1rem',
        });
    };
});

It works when the x in attribute wh='x' is set.

What I want is to make 'x' (in the angularjs script) equal to the width value given by the col-vw-x bootstrap class, so when I write:

<div href="#" class="col-sm-**x**" wh></div>

I automatically get a square div, acording to the bootstrap class.

Upvotes: 2

Views: 1653

Answers (1)

Gregori
Gregori

Reputation: 829

Here is a working plunker based on your code.

In my HTML I have:

  <div href="#" class="col-sm-4" wh style='background-color: blue;'></div>

My directive looks like:

app.directive('wh', function(){
    return function(scope, element, attrs){
      var width = attrs.class.substring(1+attrs.class.lastIndexOf('-'));
      console.log('Directive width: '+width);

        var x = element.css[width];
        element.css({
            'width': width + 'em',
            'height': width + 'em',
            'border-radius':'1rem',
        });
    };
});

Basically I read the class attributes and get col-sm-4 in my example. Look for the last '-' and get the rest of the string (i.e. 4 in my example.) Then I used your code and it works.

You may want to add some error checking in the directive as I am using indexOf and substring, but the general idea is there.

Let me know if that helps.

Upvotes: 1

Related Questions