坚持创建自定义css样式指令

Pet*_*nke 8 angularjs

对于唯一的可视化编辑器,我正在尝试创建一个写入CSS样式的新指令.当单击一个复选框使background-color属性透明时,我一直试图让指令更新.

这是我的(非工作)指令:

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();
  }
}
});
Run Code Online (Sandbox Code Playgroud)

和html元素:

<customstyle my-class="examplediv" my-transparent="settings.Window.Transparent" my-bgcolor="settings.Window.BackgroundColor"></customstyle>
Run Code Online (Sandbox Code Playgroud)

这是一个情况的错误:http://jsfiddle.net/psinke/jYQc6/

任何帮助将不胜感激.

bml*_*ite 17

尝试直接在要更改的元素上使用该指令,它更容易执行和维护.

HTML:

<div class="examplediv customstyle" 
     my-transparent="settings.Window.Transparent" 
     my-bgcolor="{{settings.Window.BackgroundColor}}">
</div>
Run Code Online (Sandbox Code Playgroud)

注意:{{settings.Window.BackgroundColor}}用于传递属性的值而不是String.

指示:

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));            
           });                      
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

注意:用于element.css()直接在元素上更改CSS属性.

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