Stuck creating a custom css style directive

后端 未结 2 757
长发绾君心
长发绾君心 2021-01-12 06:12

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 ma

相关标签:
2条回答
  • 2021-01-12 06:53

    I was having the same problem and using bmleite's solution solved it. I had a custom element with a custom attribute very similar to the one above, and changing the directive to be applied on a regular DIV instead of the custom attribute fixed it for me.


    In my solution I also have the following line of code right after the element has been modified:

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


    Remember to inject the $compile service in the directive function declaration:

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


    Thanks for a great post!

    0 讨论(0)
  • 2021-01-12 07:00

    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/

    0 讨论(0)
提交回复
热议问题