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:'='
}
};
});
1) HTML의 속성으로 콘텐츠를 전달하고 있습니다. 이 시도:
element.html(getTemplate(attrs.content)).show();
대신에:
element.html(getTemplate(scope.content)).show();
2) 지시문의 데이터 부분이 컴파일되고 있으므로 다른 것을 사용해야합니다. 데이터 유형 대신에, 예를 들어 datan 유형.
여기 링크가 있습니다:
http://jsbin.com/mibeyotu/6/edit
template
디렉티브 정의 객체 의 속성을 동적 템플릿을 반환하는 함수로 설정할 수 있습니다 .
restrict: "E",
replace: true,
template: function(tElement, tAttrs) {
return getTemplate(tAttrs.content);
}
이 시점에서는 범위에 대한 액세스 권한이 없지만을 통해 속성에 액세스 할 수 있습니다 tAttrs
.
Now your template is being determined before the compile phase, and you don't need to manually compile it.
You can also do it very straightforward like this:
appDirectives.directive('contextualMenu', function($state) {
return {
restrict: 'E',
replace: true,
templateUrl: function(){
var tpl = $state.current.name;
return '/app/templates/contextual-menu/'+tpl+'.html';
}
};
});
If you need to load your template based on $scope
variables you can do it using 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';
}
}
}
};
});
Reference: https://coderwall.com/p/onjxng/angular-directives-using-a-dynamic-template
참고URL : https://stackoverflow.com/questions/23065165/angularjs-directive-dynamic-templates
'programing tip' 카테고리의 다른 글
iTerm2 또는 OSX Lion의 터미널에서 단어 점프 (0) | 2020.11.23 |
---|---|
REST API : 단일 가져 오기에서 여러 리소스 요청 (0) | 2020.11.23 |
상수의 병적 사용 (0) | 2020.11.23 |
androidx로 마이그레이션 한 후 androidx.constraintlayout.ConstraintLayout 클래스 확장 오류 (0) | 2020.11.23 |
C에서 참조로 배열을 전달합니까? (0) | 2020.11.23 |