AngularJS에서 지시 스타일을 조작하는 방법은 무엇입니까?
Angular를 사용하여 컴포넌트를 쓰고 있습니다.JS 및 각도JS 디렉티브
저는 이렇게 하고 있습니다.
var MyApp = angular.module('MyApp', []);
MyApp.directive('myTag', function() {
return { /* Some logic here*/ }
});
(CSS를 사용하여) 컴포넌트의 스타일을 다음과 같이 변경할 수 있으면 좋겠습니다.
<my-tag class="MyClass"></my-tag>
또, 컴포넌트내의 모든 요소의 스타일(my-tag내의 HTML 마크업)을 조작할 수 있도록 하고 싶습니다.
AngularJs를 사용하여 사용자 지정 태그의 스타일 속성을 조작하는 방법에 대한 조언이나 유용한 예가 있습니까?
이거면 될 거야.
var MyApp = angular.module('MyApp', []);
MyApp.directive('myTag', function() {
return {
link: function(scope, element, attributes){
element.addClass('MyClass');
}
}
});
이게 Angular가JS는 코어 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.js v1.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>');
그럼, 을 사용할 수 있습니다.class="ouput-color"
를 참조해 주세요.
나는 그것이 매우 깨끗하고 유용하다는 것을 알았다.
파티에 조금 늦었는데 왜 다들 빌트인 .css() 메서드를 사용하지 않나요?
사용방법:
link: function(scope, elem, attr, ctrl)
{
elem.css({'display': 'block', 'height': '100%', 'width': '100%'});
}
네가 원하는 어떤 css라도.
예시와 같이 매개변수를 사용하여 지시문의 선언에 사용자 정의 스타일을 넣을 수 있습니다.
이러한 스타일을 선언하려면 사용자 정의 스타일을 유지할 변수를 정의해야 합니다.
scope: {
myClass: '@myClass'
},
그런 다음 지시문 템플릿에서 다음과 같이 매개 변수를 설정합니다.
<my-tag my-class="CustomClass"></my-tag>
마지막으로 디렉티브 자체의 템플릿에서 해당 클래스를 참조합니다.
<h1 class="{{myClass}}">{{myContent}}</h1>
디렉티브로 스타일을 커스터마이즈할 수 있는 방법을 보여주는 플런커를 만들었습니다.여기에서 확인하세요. .
Atribute Directive 를 사용해 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));
});
}
};
});
일부 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>
요소 지시어를 만들려면 다음과 같이 고유한 스타일을 변경합니다.
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">
<element-with-style>123</element-with-style>
</div>
이게 도움이 됐으면 좋겠어요.나머지 답들은 어느 정도 학급 조작을 다루고 있다.
디렉티브의 자녀 내에서 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';
}
}
}
});
예를 들어, 이것은 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);
}
};
});
마지막으로, 마크업에 이것을 입력합니다.
<my-tag />
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>
각진
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>
아직 완벽한 솔루션을 찾지 못했지만, John Papa의 컨트롤러 스타일링을 따르고 있습니다.
- 디렉티브는 폴더(directiveName.directive)입니다.
- 3개의 파일: directiveName.directive.js, directiveName.template.html, directiveName.styles.css
- 디렉티브를 선언할 때 templateUrl을 사용합니다.템플릿에는 통상대로 css 파일에 대한 링크가 있습니다.
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 개를 입니다.<link>
태그는 렌더링된 HTML의 지시어 근처에 있습니다(단, 아직 문제가 되지 않은 것 같습니다).이 댓글도 봐주세요.
즉, Angular 1.5의 컴포넌트를 살펴보십시오.비교적 새롭고 접근법이 훨씬 우수합니다.현재는 DOM 조작에만 디렉티브를 사용하고 있습니다(컴포넌트로 재사용할 수 없습니다).
언급URL : https://stackoverflow.com/questions/19246110/how-to-manipulate-styles-of-directive-in-angularjs
'programing' 카테고리의 다른 글
mongodb는 실행 중입니까? (0) | 2023.03.28 |
---|---|
React Native Flat List의 List Header Component를 스틱으로 만들려면 어떻게 해야 합니까? (0) | 2023.03.28 |
데이터베이스 내의 모든 문자열 인스턴스를 검색 및 치환하려면 어떻게 해야 합니까? (0) | 2023.03.28 |
jq를 사용하여 키 이름을 다른 이름으로 바꾸려면 어떻게 해야 합니까? (0) | 2023.03.28 |
프로젝터와 카르마를 함께 사용할 수 있습니까? (0) | 2023.03.28 |