Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck creating a custom css style directive

Tags:

angularjs

For an only visual editor I'm trying to create a new directive that writes a CSS style. I'm stuck at trying to get the directive to update when a checkbox is clicked to make the background-color property transparent.

Here's my (non-working) directive:

myApp.directive('customstyle', function () {
return {
    restrict: 'E',
    link: function (scope, element, attrs) {
      var bgColor;
      scope.$watch(attrs.myTransparent, function (value) {
        if (value) {
          bgColor = 'transparent';
        } else {
          bgColor = attrs.myBgcolor;
        }
        updateStyle();
      }, true);

      function updateStyle() {
        var htmlText = '<style>.' + attrs.myClass + '{';
        htmlText += 'background-color: ' + bgColor + ';';
        htmlText += "}</style>";
        element.replaceWith(htmlText);
      }
      updateStyle();
  }
}
});

and html element:

<customstyle my-class="examplediv" my-transparent="settings.Window.Transparent" my-bgcolor="settings.Window.BackgroundColor"></customstyle>

Here's a jsfiddle of the situation: http://jsfiddle.net/psinke/jYQc6/

Any help would be greatly appreciated.

like image 729
Peter Sinke Avatar asked Jan 14 '13 12:01

Peter Sinke


1 Answers

Try using the directive directly on the element you want to change, it's easier to do and to maintain.

HTML:

<div class="examplediv customstyle" 
     my-transparent="settings.Window.Transparent" 
     my-bgcolor="{{settings.Window.BackgroundColor}}">
</div>

Note: Use {{settings.Window.BackgroundColor}} to pass the property's value and not a String.

Directive:

myApp.directive('customstyle', function () {
    return {
        restrict: 'AC',
        link: function (scope, element, attrs) {          
           scope.$watch(attrs.myTransparent, function (value) {     
             element.css('background-color', (value ? 'transparent' : attrs.myBgcolor));            
           });                      
        }
    }
});

Note: Use element.css() to change CSS properties directly on the element.

jsFiddler: http://jsfiddle.net/jYQc6/8/

like image 104
bmleite Avatar answered Sep 28 '22 09:09

bmleite