Stéphane de Luca
Stéphane de Luca

Reputation: 13583

How to style a directive from the outside?

I have a directive which I want to customize with style attribute from where I invoke it, as follows:

<plant-stages style="-webkit-transform: scale(.8); border: solid blue 1px"
    stages="stages"
    affectedstages="accident.stages"
    change-page="changePage(stage)"
    title="Les étapes du cycle suceptibles d'être affectées"
    subtitle="Taper sur une des étape de la plante pour obtenir des informations détaillées"
></plant-stages>

By passing in style attributes, I'd like they apply to the resulting HTML from the directive, as any standard HTML directive would do.

The partial code snippet is as follows:

<figure class="cornStages">
    <div></div>
</figure>

And the directive itself is as follows:

app.directive('plantStages', function ($compile) {
    return {
        restrict: 'E',
        templateUrl: 'corn.figure.plant.stages.html',
        transclude: true,
        scope: { 
            stages: "=",
            affectedstages:"=",
            changePage: "&",
            title: "@",
            subtitle : "@"
        },

Any idea?

Upvotes: 1

Views: 80

Answers (1)

Julien
Julien

Reputation: 2246

One option could be to store the style in the scope by adding style: '@' in the definition of the scope of the directive and then to add ng-style="style" in your template.

I've made a working example on JS Fiddle.

The code is the following:

HTML

<div ng-app="myApp">
    <my-little-directive style="color: red"></my-little-directive>
    <my-little-directive style="color: blue"></my-little-directive>
    <my-little-directive style="-webkit-transform: scale(.8); border: solid blue 1px"></my-little-directive>
</div>

Javascript

angular.module('myApp',[]).directive('myLittleDirective', function() {
   return {
        restrict: 'E',
       template: '<div ng-style="style">{{style}}</div>',
        replace: true,
        scope: { 
            style : "@"
        },
};
});

Upvotes: 1

Related Questions