1

I am trying to move styles for a number of elements from a less file into an angular directive. I have created directives already but am unclear how this should be done.

For example, if I have a html file like below:

   <div mylessDirective>
       <div class="style1">Hello World</div>
       <div class="style2">Hello World2</div>
       <div class="style3">Hello World3</div>
   <div>

Here I have 3 divs with 3 different styles, style 1 and style 2 and style 3. Is it possible to call a directive (mylessDirective) as shown that contains all the less styles associated with this class, so that it picks them up. If so can anyone suggest how this directive should be done, for example if I wanted to set a different background colour for each of the three styles. Thanks for the help!

2
  • less/css is the appropriate tool for that. Why would you need a directive? Just define all the CSS styles that a style1 element must have into the style1 class definition in your less/css stylesheet. Commented Jul 8, 2015 at 16:30
  • Also note that Less code must be compiled to CSS before it can be understood by a browser. So unless Angular has built-in ability to compile Less you can't use Less code inside those directives (only plain CSS). Commented Jul 8, 2015 at 19:43

2 Answers 2

1

You could use the ngClass directive and construct your own style names:

<div>
   <div ng-class="style1">Hello World</div>
   <div ng-class="style2">Hello World2</div>
   <div ng-class="style3">Hello World3</div>
<div>
Sign up to request clarification or add additional context in comments.

Comments

0

Don't know if I understood well but I think this is a good approach to the general issue about directive and CSS styling:

JSFiddle

HTML:

<div ng-app="myApp">
    <div myless-directive>
       <div ng-style="style1">Hello World</div>
       <div ng-style="style2">Hello World2</div>
       <div ng-style="style3">Hello World3</div>
   <div>
</div>

JS:

angular.module('myApp', [])
    .directive('mylessDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            scope.style1 = {'background-color': 'red'}; 
            scope.style2 = {'background-color': 'green'}; 
            scope.style3 = {'background-color': 'blue'}; 
        }
    };
});

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.