Html 如何在 AngularJS 中操作指令样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19246110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to manipulate styles of directive in AngularJS?
提问by Roman Dryndik
I'm writing a component using AngularJS and AngularJS directives.
我正在使用 AngularJS 和 AngularJS 指令编写一个组件。
I'm doing something like this:
我正在做这样的事情:
var MyApp = angular.module('MyApp', []);
MyApp.directive('myTag', function() {
return { /* Some logic here*/ }
});
I want to be able to change style of my component (using CSS), something like this:
我希望能够更改组件的样式(使用 CSS),如下所示:
<my-tag class="MyClass"></my-tag>
Besides this I want to be able to manipulate all elements style inside my component (HTML markup inside of my-tag).
除此之外,我希望能够操纵组件内的所有元素样式(my-tag 内的 HTML 标记)。
Do you have any advice or useful examples how to manipulate the style properties of custom tags using AngularJS?
你有什么建议或有用的例子如何使用 AngularJS 操作自定义标签的样式属性吗?
回答by Ben
This should do the trick.
这应该可以解决问题。
var MyApp = angular.module('MyApp', []);
MyApp.directive('myTag', function() {
return {
link: function(scope, element, attributes){
element.addClass('MyClass');
}
}
});
回答by Andrei
This is how AngularJS adds core CSS styles:
这是 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>');
You can find this code in angular.js v1.2.0-rc.2.
您可以在 angular.js v1.2.0-rc.2 中找到此代码。
EDIT
编辑
In a custom directive, I use this solution to bundle CSS stylesheets in the directive:
在自定义指令中,我使用此解决方案在指令中捆绑 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>');
Then you can use class="ouput-color"
in your directive templates.
然后你可以class="ouput-color"
在你的指令模板中使用。
I found it very clean and useful.
我发现它非常干净和有用。
回答by Porlune
I'm a little late to the party, but why aren't you all using the built in .css() method?
我参加聚会有点晚了,但为什么你们不都使用内置的 .css() 方法?
just use:
只需使用:
link: function(scope, elem, attr, ctrl)
{
elem.css({'display': 'block', 'height': '100%', 'width': '100%'});
}
or whatever css you desire.
或任何你想要的 css。
回答by Julian
You can put custom styles in a directive's declaration with a parameter, just like you exemplified.
您可以使用参数将自定义样式放在指令的声明中,就像您举例说明的那样。
In order to declare a style like that, you have to define a variable to hold the custom styles:
为了声明这样的样式,您必须定义一个变量来保存自定义样式:
scope: {
myClass: '@myClass'
},
And then set that parameter in the directive's template, like this:
然后在指令的模板中设置该参数,如下所示:
<my-tag my-class="CustomClass"></my-tag>
Finally, in the template of the directive itself, reference that class:
最后,在指令本身的模板中,引用该类:
<h1 class="{{myClass}}">{{myContent}}</h1>
I made a plunker that shows how you can customize styles in a directive, check it out here.
我制作了一个 plunker,展示了如何在指令中自定义样式,请在此处查看。
回答by AturSams
To manipulate the css style through an attribute directive, you could do something like this:
要通过属性指令操作 css 样式,您可以执行以下操作:
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));
});
}
};
});
Some html:
一些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>
To make an element directive, change it's own style, something like this:
要制作元素指令,请更改它自己的样式,如下所示:
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>'
}
});
And the html:
和 html:
<div ng-app="colorSwap">
<element-with-style>123</element-with-style>
</div>
I hope this helps. The rest of the answers cover class manipulation more or less.
我希望这有帮助。其余的答案或多或少涵盖了类操作。
回答by Germando
For css manipulation inside of the childs of your directive try this:
对于指令的孩子内部的 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';
}
}
}
});
回答by francisco.preller
Here is an example, please note that this is probably not the best use of AngularJS, being declarative, you would likely want to just put the classes on the markup. However, just so you understand what's going on, let me demonstrate a simple directive to do what you first asked.
这是一个示例,请注意这可能不是 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);
}
};
});
Finally, on your markup, you just put this in:
最后,在您的标记上,您只需将其放入:
<my-tag />
回答by Rajat Sawant
Angular
角
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
HTML
The times is <span time></span>
回答by Mahesh K
app.directive('bookslist', function() {
return {
scope: true,
templateUrl: 'templates/bookslist.html',
restrict: "E",
controller: function($scope){
},
link: function(scope, element, attributes){
element.addClass('customClass');
}
}
});
.customClass table{
background: tan;
}
.customClass td{
border: 1px solid #ddd;
}
<!DOCTYPE html>
<html>
<head>
<link href="app.css" rel="stylesheet">
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<title>Task</title>
</head>
<body ng-app="app">
<div ng-controller="myCtrl">
<bookslist></bookslist>
</div>
</body>
</html>
回答by Z. Khullah
I didn't found the perfect solution just yet, but I'm following John Papa's stylingof controllers even with directives:
我还没有找到完美的解决方案,但即使有指令,我也遵循John Papa 的控制器样式:
- the directive is a folder (directiveName.directive)
- 3 files inside: directiveName.directive.js, directiveName.template.html, directiveName.styles.css
- use templateUrl when declaring the directive. The template has the link to the css file, as usual
- 指令是一个文件夹 (directiveName.directive)
- 里面的 3 个文件:directiveName.directive.js、directiveName.template.html、directiveName.styles.css
- 声明指令时使用 templateUrl。像往常一样,模板具有指向 css 文件的链接
I found it to be very clean and follows a pattern. The bad side of it is that you create several <link>
tags near the directives in the rendered HTML (not seem to be a issue still, though). Check out this commenttoo.
我发现它非常干净并且遵循一种模式。它的坏处是您<link>
在呈现的 HTML 中的指令附近创建了几个标签(不过似乎仍然不是问题)。也看看这个评论。
That being said, take a look at Angular 1.5 component's. It's relatively new and has a much better approach. Now I use directives only for DOM manipulation (not reusability as components).
话虽如此,看看Angular 1.5 组件的. 它相对较新,并且有更好的方法。现在我只将指令用于 DOM 操作(而不是作为组件的可重用性)。