반응형
AngularJS 지시 다이내믹 템플릿
스코프 값에 따라 다른 템플릿으로 디렉티브를 작성하려고 합니다.
지금까지 한 일이지만 왜 안 되는지 모르겠다.http://jsbin.com/mibeyotu/1/edit
HTML 요소:
<data-type content-attr="test1"></data-type>
지시:
var app = angular.module('myApp', []);
app.directive('dataType', function ($compile) {
var testTemplate1 = '<h1>Test1</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var getTemplate = function(contentType){
var template = '';
switch(contentType){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}
return template;
};
var linker = function(scope, element, attrs){
element.html(getTemplate(scope.content)).show();
$compile(element.contents())(scope);
};
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content:'='
}
};
});
를 설정할 수 있습니다.template
동적 템플릿을 반환하는 함수에 대한 지시 정의 개체의 속성:
restrict: "E",
replace: true,
template: function(tElement, tAttrs) {
return getTemplate(tAttrs.content);
}
현시점에서는 스코프에 액세스 할 수 없습니다만, 다음의 방법으로 속성에 액세스 할 수 있습니다.tAttrs
.
이제 템플릿은 컴파일 단계 전에 결정되므로 수동으로 컴파일할 필요가 없습니다.
다음과 같이 간단하게 할 수도 있습니다.
appDirectives.directive('contextualMenu', function($state) {
return {
restrict: 'E',
replace: true,
templateUrl: function(){
var tpl = $state.current.name;
return '/app/templates/contextual-menu/'+tpl+'.html';
}
};
});
1) 콘텐츠를 html 속성으로 전달합니다.이것을 시험해 보세요.
element.html(getTemplate(attrs.content)).show();
다음 대신:
element.html(getTemplate(scope.content)).show();
2) 디렉티브의 데이터 부분은 컴파일 중이므로 다른 것을 사용해야 합니다.데이터 유형(예: datan-type)이 아닌
다음은 링크입니다.
http://jsbin.com/mibeyotu/6/edit
다음을 기준으로 템플릿을 로드해야 하는 경우$scope
사용할 수 있는 변수ng-include
:
.directive('profile', function() {
return {
template: '<ng-include src="getTemplateUrl()"/>',
scope: {
user: '=data'
},
restrict: 'E',
controller: function($scope) {
//function used on the ng-include to resolve the template
$scope.getTemplateUrl = function() {
//basic handling
if ($scope.user.type == 'twitter') {
return 'twitter.tpl.html';
}
if ($scope.user.type == 'facebook') {
return 'facebook.tpl.html';
}
}
}
};
});
참고 자료: https://coderwall.com/p/onjxng/angular-directives-using-a-dynamic-template
언급URL : https://stackoverflow.com/questions/23065165/angularjs-directive-dynamic-templates
반응형
'sourcecode' 카테고리의 다른 글
Json을 사용하여 이종 JSON 어레이를 공변량 목록으로 역직렬화 <>.그물 (0) | 2023.03.05 |
---|---|
빈 등록 httpSessionManager가 중복되어 Spring Boot 2.1에서 Keycloak을 사용할 수 없습니다. (0) | 2023.03.05 |
같은 스테이트먼트에서 입력과 집약을 어떻게 사용하는가? (0) | 2023.03.05 |
Larabel에 JSON 게시 (0) | 2023.02.28 |
기본 통화 기호(달러 기호)가 아닌 각도 js에서 특정 통화 기호(내 경우 루피 기호)를 가져오는 방법 (0) | 2023.02.28 |