Javascript 如何操作AngularJS中的指令样式?

Javascript 如何操作AngularJS中的指令样式?,javascript,html,css,angularjs,angularjs-directive,Javascript,Html,Css,Angularjs,Angularjs Directive,我正在使用AngularJS和AngularJS指令编写一个组件 我在做这样的事情: var MyApp = angular.module('MyApp', []); MyApp.directive('myTag', function() { return { /* Some logic here*/ } }); <my-tag class="MyClass"></my-tag> <my-tag my-class="CustomClass">&l

我正在使用AngularJS和AngularJS指令编写一个组件

我在做这样的事情:

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function() {
    return { /* Some logic here*/ }
});
<my-tag class="MyClass"></my-tag>
<my-tag my-class="CustomClass"></my-tag>
var app = angular.module('colorSwap', []);

app.directive('styleChanger', function() {
  return {
    'scope': false,
    'link': function(scope, element, attrs) {
      var someFunc = function(data)
      {
        /* does some logic */
        return 'background-color:' + data;
      }
      var newStyle = attrs.styleChanger;
      scope.$watch(newStyle, function (style) {
        if (!style) {
          return ;
        }
        attrs.$set('style', someFunc(style));
      });
    }
  };
});
app.directive('elementWithStyle', function() {
  return {
    'restrict' : 'E',
    'scope': {},
    'controller': function($scope) {
      $scope.someStyle = 'Cyan';
      $scope.someFunc = function() { $scope.someStyle = 'purple' };
    },
    'template': '<div style="background: {{someStyle}}" ng-click="someFunc()"> click me to change colors </div>'
  }
});
我希望能够更改组件的样式(使用CSS),如下所示:

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function() {
    return { /* Some logic here*/ }
});
<my-tag class="MyClass"></my-tag>
<my-tag my-class="CustomClass"></my-tag>
var app = angular.module('colorSwap', []);

app.directive('styleChanger', function() {
  return {
    'scope': false,
    'link': function(scope, element, attrs) {
      var someFunc = function(data)
      {
        /* does some logic */
        return 'background-color:' + data;
      }
      var newStyle = attrs.styleChanger;
      scope.$watch(newStyle, function (style) {
        if (!style) {
          return ;
        }
        attrs.$set('style', someFunc(style));
      });
    }
  };
});
app.directive('elementWithStyle', function() {
  return {
    'restrict' : 'E',
    'scope': {},
    'controller': function($scope) {
      $scope.someStyle = 'Cyan';
      $scope.someFunc = function() { $scope.someStyle = 'purple' };
    },
    'template': '<div style="background: {{someStyle}}" ng-click="someFunc()"> click me to change colors </div>'
  }
});

除此之外,我希望能够操纵我的样式中的所有元素 组件(我的标记中的HTML标记)


你对如何使用AngularJS操作自定义标记的样式属性有什么建议或有用的例子吗?

这应该可以做到

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function() {
    return { 
      link: function(scope, element, attributes){
        element.addClass('MyClass');
      }
    }
});

这里是一个例子,请注意,这可能不是AngularJS的最佳用途,因为它是声明性的,您可能只想将类放在标记上。然而,为了让您了解发生了什么,让我演示一个简单的指令来完成您最初要求的操作

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function($compile) {
    return {
        restrict: 'E', // this means it will be an element
        link: function(scope, element, attrs, ctrl) {
            // First, I included the $compile service because it will be needed
            // to compile any markup you want to return to the element.

            // 1. Add the class, as you wanted
            element.addClass('MyClass');

            // 2. Add markup
            var html = '<div>Hello World</div>';
            //Compile it and add it back
            $compile(html)(scope);
            element.html(html);
        }
    };
});
var MyApp=angular.module('MyApp',[]);
MyApp.directive('myTag',函数($compile){
返回{
restrict:'E',//这意味着它将是一个元素
链接:函数(范围、元素、属性、ctrl){
//首先,我包括$compile服务,因为它是必需的
//编译要返回到元素的任何标记。
//1.根据需要添加类
元素addClass('MyClass');
//2.添加标记
var html='Hello World';
//编译并重新添加它
$compile(html)(范围);
html(html);
}
};
});
最后,在您的标记上,您只需将以下内容放入:

<my-tag />

AngularJS就是这样添加核心CSS样式的:

angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}</style>');
angular.element(document).find('head').prepend('@charset“UTF-8”;[ng\\:斗篷],[ng斗篷],[data-ng斗篷],.ng斗篷,.x-ng-斗篷,.ng隐藏{display:none!重要;}ng\\:form{display:block;});
您可以在angular.jsv1.2.0-rc.2中找到这段代码

编辑 在自定义指令中,我使用此解决方案将CSS样式表捆绑到指令中:

  var outputColorCSS = {
    selector: 'span.ouput-color',
    rules: [
        'display: inline-block',
        'height: 1em',
        'width: 5em',
        'background: transparent',
        'border: 3px solid black',
        'text-align: center',
        'font-weight: bold',
        'font-size: 0.8em'
    ]
  };
  var outputColorStyleSheet = outputColorCSS.selector + outputColorCSS.rules.join(';');
  angular.element(document).find('head').prepend('<style type="text/css">' + outputColorStyleSheet + '</style>');
var outputColorCSS={
选择器:“span.output color”,
规则:[
'显示:内联块',
“高度:1米”,
“宽度:5em”,
'背景:透明',
'边框:3倍纯黑',
'文本对齐:居中',
'字体大小:粗体',
'字体大小:0.8em'
]
};
var outputColorStyleSheet=outputColorCSS.selector+outputColorCSS.rules.join(“;”);
angular.element(document).find('head').prepend(''+outputColorStyleSheet+'');
然后可以在指令模板中使用
class=“ouput color”


我发现它非常干净和有用。

您可以使用参数将自定义样式放入指令的声明中,就像您举例说明的那样

为了声明这样的样式,必须定义一个变量来保存自定义样式:

scope: {
    myClass: '@myClass'
  },
然后在指令的模板中设置该参数,如下所示:

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function() {
    return { /* Some logic here*/ }
});
<my-tag class="MyClass"></my-tag>
<my-tag my-class="CustomClass"></my-tag>
var app = angular.module('colorSwap', []);

app.directive('styleChanger', function() {
  return {
    'scope': false,
    'link': function(scope, element, attrs) {
      var someFunc = function(data)
      {
        /* does some logic */
        return 'background-color:' + data;
      }
      var newStyle = attrs.styleChanger;
      scope.$watch(newStyle, function (style) {
        if (!style) {
          return ;
        }
        attrs.$set('style', someFunc(style));
      });
    }
  };
});
app.directive('elementWithStyle', function() {
  return {
    'restrict' : 'E',
    'scope': {},
    'controller': function($scope) {
      $scope.someStyle = 'Cyan';
      $scope.someFunc = function() { $scope.someStyle = 'purple' };
    },
    'template': '<div style="background: {{someStyle}}" ng-click="someFunc()"> click me to change colors </div>'
  }
});

最后,在指令本身的模板中,引用该类:

<h1 class="{{myClass}}">{{myContent}}</h1>
{{myContent}

我制作了一个plunker,展示了如何在指令中自定义样式。

对于指令的子指令内部的css操作,请尝试以下方法:

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function() {
    return { 
      link: function(scope, element, attr){

       // For your tag
       element.addClass('MyClass');

       // For elements inside your directive tag
       var tag_childs = element[0].childNodes;
       for(var i = 0; i < element[0].childElementCount; i++){

          tag_childs[i].style.height = '70px';

        }

      }
    }
});
var MyApp=angular.module('MyApp',[]);
MyApp.directive('myTag',function(){
返回{
链接:功能(范围、元素、属性){
//为了你的标签
元素addClass('MyClass');
//用于指令标记内的元素
var tag_childs=元素[0]。childNodes;
对于(变量i=0;i<元素[0]。childElementCount;i++){
tag_childs[i].style.height='70px';
}
}
}
});

要通过属性指令操纵css样式,可以执行以下操作:

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function() {
    return { /* Some logic here*/ }
});
<my-tag class="MyClass"></my-tag>
<my-tag my-class="CustomClass"></my-tag>
var app = angular.module('colorSwap', []);

app.directive('styleChanger', function() {
  return {
    'scope': false,
    'link': function(scope, element, attrs) {
      var someFunc = function(data)
      {
        /* does some logic */
        return 'background-color:' + data;
      }
      var newStyle = attrs.styleChanger;
      scope.$watch(newStyle, function (style) {
        if (!style) {
          return ;
        }
        attrs.$set('style', someFunc(style));
      });
    }
  };
});
app.directive('elementWithStyle', function() {
  return {
    'restrict' : 'E',
    'scope': {},
    'controller': function($scope) {
      $scope.someStyle = 'Cyan';
      $scope.someFunc = function() { $scope.someStyle = 'purple' };
    },
    'template': '<div style="background: {{someStyle}}" ng-click="someFunc()"> click me to change colors </div>'
  }
});
一些html:

<div ng-app="colorSwap">
  <input type="txt" ng-init="colorName= 'yellow'" ng-model="colorName" />
  <div style-changer="colorName">this is the div content</div>
</div>

这是div的内容
要生成元素指令,请更改其自身的样式,如下所示:

var MyApp = angular.module('MyApp', []);

MyApp.directive('myTag', function() {
    return { /* Some logic here*/ }
});
<my-tag class="MyClass"></my-tag>
<my-tag my-class="CustomClass"></my-tag>
var app = angular.module('colorSwap', []);

app.directive('styleChanger', function() {
  return {
    'scope': false,
    'link': function(scope, element, attrs) {
      var someFunc = function(data)
      {
        /* does some logic */
        return 'background-color:' + data;
      }
      var newStyle = attrs.styleChanger;
      scope.$watch(newStyle, function (style) {
        if (!style) {
          return ;
        }
        attrs.$set('style', someFunc(style));
      });
    }
  };
});
app.directive('elementWithStyle', function() {
  return {
    'restrict' : 'E',
    'scope': {},
    'controller': function($scope) {
      $scope.someStyle = 'Cyan';
      $scope.someFunc = function() { $scope.someStyle = 'purple' };
    },
    'template': '<div style="background: {{someStyle}}" ng-click="someFunc()"> click me to change colors </div>'
  }
});
app.directive('elementWithStyle',function(){
返回{
“限制”:“E”,
'范围':{},
“控制器”:函数($scope){
$scope.someStyle='Cyan';
$scope.someFunc=function(){$scope.someStyle='purple'};
},
“模板”:“单击我更改颜色”
}
});
以及html:

<div ng-app="colorSwap">
  <element-with-style>123</element-with-style>
</div>

123

我希望这有帮助。其余的答案或多或少涉及到类操作。

我参加聚会有点晚,但为什么你们都不使用内置的.css()方法呢

只需使用:

link: function(scope, elem, attr, ctrl)
{
    elem.css({'display': 'block', 'height': '100%', 'width': '100%'});

}
或者任何你想要的css。

app.directive('bookslist',function(){
返回{
范围:正确,
templateUrl:'templates/bookslist.html',
限制:“E”,
控制器:功能($scope){
},
链接:功能(范围、元素、属性){
元素addClass('customClass');
}
}
});
.customClass表{
背景:谭;
}
.海关关卡{
边框:1px实心#ddd;
}

任务

我还没有找到完美的解决方案,但即使有指令,我也会遵循以下控制器:

  • 该指令是一个文件夹(directiveName.directive)
  • 里面有3个文件:directiveName.directive.js、directiveName.template.html、directiveName.styles.css
  • 声明指令时使用templateUrl。模板像往常一样有到css文件的链接
我发现它非常干净,并且遵循一种模式。不好的一面是,在呈现的HTML中的指令附近创建了几个
标记(不过这似乎还不是个问题)。也退房


话虽如此,请看一看。它相对较新,有一个更好的方法。现在我只对DOM操作使用指令(而不是作为组件重用)。

app.directive("time",function(){
            var directive={};
            directive.restrict="A";
            directive.link=function(scope,element,attr,ctrl){                   
                element.css({
                    backgroundColor:'#ead333'
                });
            }
            var time=new Date().toTimeString();
            directive.template=time;
            return directive;
        });
HTML

The times is <span time></span>
时代已经来临

所以,我必须在指令中输入类的名称,对吗?如果是这样的话,我认为这不是一个好的解决方案…也许这就是你所追求的,为什么这是一个投票站在所有??探索