8

唯一のビジュアルエディターとして、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();
  }
}
});

およびhtml要素:

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

これが状況のjsfiddleです:http://jsfiddle.net/psinke/jYQc6/

どんな助けでも大歓迎です。

4

2 に答える 2

17

変更する要素に直接ディレクティブを使用してみてください。実行と保守が簡単です。

HTML:

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

注:{{settings.Window.BackgroundColor}}文字列ではなく、プロパティの値を渡すために使用します。

指令:

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));            
           });                      
        }
    }
});

注:element.css()要素で直接CSSプロパティを変更するために使用します。

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

于 2013-01-14T14:03:51.373 に答える
1

私は同じ問題を抱えていて、bmleiteのソリューションを使用してそれを解決しました。上記と非常によく似たカスタム属性を持つカスタム要素があり、カスタム属性の代わりに通常のDIVに適用されるようにディレクティブを変更すると修正されました。


私のソリューションでは、要素が変更された直後に次のコード行もあります。

  $compile(element.contents())(scope);


ディレクティブ関数宣言に$compileサービスを挿入することを忘れないでください。

  myApp.directive('directiveName', function ($compile) { ...


素晴らしい投稿をありがとう!

于 2013-05-08T22:00:13.550 に答える