각도 지시어 다른 템플릿
myDirective의 다이렉트 타입은 가변형입니다.내가 뛰면<my-directive type="X">
디렉티브는 templateUrl:x-template.html을 사용합니다.내가 하면<my-directive type="Y">
디렉티브에서 templateUrl: y-template.html을 사용합니다.
이게 제 현재 지시사항입니다
app.directive('myDirective', function() {
var myDirective = {
templateUrl: 'X-template.html',
restrict: 'E',
scope: {
type: '='
},
};
return myDirective;
});
stackoverflow와 angular documentation을 읽었지만 필요한 것을 찾지 못했습니다.
저는 지금 다음과 같은 일을 하려고 합니다.
if ($scope.type === 'X') {
templateUrl: 'X-template.html',
}
else if ($scope.type === 'Y') {
templateUrl: 'Y-template.html',
}
하지만 어디서 해야 할지 모르겠다.
이게 가능한지, 어떻게 가능한지 아세요?
Angular는 함수를 템플릿 옵션으로 받아들이므로 다음과 같은 작업을 수행할 수 있습니다.
.directive('myDirective', function () {
return {
templateUrl: function (tElement, tAttrs) {
if (tAttrs) {
if (tAttrs.type === 'X') {
return 'X-template.html';
}
if (tAttrs.type === 'Y') {
return 'Y-template.html';
}
}
}
}
});
자세한 내용은 $compile 서비스 설명서를 참조하십시오.
이 문제를 해결하려면 다음 방법으로 해결할 수 있습니다.ng-include
안에서.compile
:
app.directive('myDirective', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
element.append('<div ng-include="\'' + attrs.type + '-template.html\'"></div>');
}
}
});
1.1.x 코드 패스에 빌드를 붙이고 있는 경우(각 1.1.x 빌드 노트의 엔트리에 첨부된 경고에 주목해, 여기서 반복해 이 답변을 희석하지 않도록 해 주세요), 이 기능은 4월 3일의 1.1.4 릴리스에서 새롭게 추가되었습니다.1.1.4 릴리즈 노트는 여기에서 찾을 수 있습니다.기능의 태스크로그에는 신기능의 사용방법을 나타내는 Jasmine 테스트가 포함되어 있습니다.
1.0.x 릴리스를 사용하는 경우 보다 보수적이면 쉽게 이 작업을 수행할 수 없지만 수행할 수 있습니다.Mark Rajcok의 솔루션은 현재 고객의 요건에 맞는 것 같습니다.단, 몇 가지 주의사항을 덧붙이겠습니다.
- 1.1.4 릴리즈를 제외하고 컴파일 시간 디렉티브는 실행 시 수정을 지원하지 않습니다.
- 1.1.4부터는 컴파일 시간 지시어의 속성을 안전하게 변경할 수 있지만 다른 컴파일 시간 지시문에서만 변경할 수 있습니다.
- 다음 사항을 고려해 보십시오.
replaceWith()
대신append()
부터<my-directive>
는 표준 정의 HTML 요소 유형이 아닙니다. - Y에 추가X 템플릿의 할 수
<my-template>
템플릿의 루트 요소에 쉽게 접근할 수 있습니다.- replace: true 명령어는 소스 요소에서 치환 루트로 속성을 전송하지만 이 명령어는 그렇지 않다고 생각합니다.
ngInclude
는 is host에서 포함된 템플릿의 루트까지 동일한 작업을 수행합니다. - 나도 기억나는 것 같아
ngInclude
에서는 템플릿에 루트 요소가1개만 있을 필요는 없습니다. - 를 사용하여 대체 부모에 대한 속성을 유지할 수 있습니다.
replaceWith()
append()
★★★★★★★★★★★★★★★★★★★★★<div ng-include="">
를 달다<div></div>
... 우터 . .<div>
수 있으며 Atribute, Atribute 뒤에 액세스할 수 있습니다.<div ngInclude>
요소가 로드된 콘텐츠로 대체되었습니다.
- replace: true 명령어는 소스 요소에서 치환 루트로 속성을 전송하지만 이 명령어는 그렇지 않다고 생각합니다.
- 「 」는 .
ngInclude
새로운 스코프가 생성됩니다.그러면 기본 스코프 모델의 위험성에 대한 경고 메시지가 노란색으로 깜박입니다.자세한 내용은 Angular의 GitHub 디포에서 이 페이지를 참조하십시오.
1.0.x에 대해서는 다른 대안을 제안할 수 있지만, 상당한 양의 코드가 필요합니다.좀 더 무거운 작업이지만 템플릿 간 전환뿐만 아니라 본격적인 지시도 가능하다는 장점이 있습니다.게다가, 그 동작은 보다 쉽게 역동적입니다.
app.directive('myDirective', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'partials/directive/my-directive.html',
link: function(scope, element, attrs, ctrl) {
// You can do this with isolated scope as well of course.
scope.type = attrs.type;
}
}
);
my-displaces.displaces
<div ng-switch on="{{type}}">
<div ng-switch-where="X" ng-include="X-template.html"></div>
<div ng-switch-where="Y" ng-include="Y-template.html"></div>
</div>
my-displaces.displaces
이것은 옵션에서 기본 템플릿을 재정의하기 위한 버전입니다.
templateUrl: function (elem, attrs) {
if (attrs.customTemplate) {
return '/path/to/components/tmpl/' + attrs.customTemplate + '.html';
} else {
return '/path/to/components/tmpl/directive.html';
}
}
예를 들어 지령에 따라
<div my-directive custom-template="custom"></div>
나는 이 문제를 해결한다.
app.directive("post", function ($templateCache, $compile) {
function getTemplate(mode) {
switch (mode) {
case "create":
return "createPost.html";
case "view":
return "viewPost.html";
case "delete":
return "deletePost.html";
}
}
var defaultMode = "view";
return {
scope: {},
restrict: "AE",
compile: function (elem, attrs, transclude) {
return function ($scope, $element, $attr) {
function updateTemplate() {
$element.html("");
$compile($templateCache.get(getTemplate($scope.mode)).trim())($scope, function (clonedElement, scope) {
clonedElement.appendTo($element);
});
}
$scope.mode = $attr.mode || defaultMode;
$scope.$watch("mode", updateTemplate);
}
}
}
});
최선의 방법은 아닐지도 모르지만, 저는 여분의 범위가 없습니다.
좋아요, 여기 있는 누군가에게 도움이 될 수도 있어요:-)
링크 또는 컨트롤러 기능에 커스텀 속성을 삽입하려면 다음 명령을 사용합니다.
지금은 일하고 있습니다만, 나중에 기회가 되면 바이올린을 투고하겠습니다:-)
.directive('yourDirective', function() {
return {
restrict: 'EA',
template: '<div></div>', // or use templateUrl with/without function
scope: {
myAttibute: '@myAttr' // adds myAttribute to the scope
},
link: function(scope) {
console.log(scope.myAttibute);
}
}
}
// HTML " "
// 콘솔이 "foo"를 출력합니다.
언급URL : https://stackoverflow.com/questions/16490382/angular-directive-different-template
'programing' 카테고리의 다른 글
(노드:9374) 경고:ES 모듈을 로드하려면 "type"을 설정합니다. "module" (0) | 2023.04.02 |
---|---|
Woocommerce: 사용자 입력에 따른 맞춤 가격 (0) | 2023.04.02 |
for loop에서 ajax 콜백 함수로 인덱스 전달(JavaScript) (0) | 2023.04.02 |
'../build/Release/bson' 모듈을 찾을 수 없습니다. 코드: 'MODULE_NOT_FOUND' } js-bson:순수 JS 버전을 사용하여 c++ bson 확장을 로드하지 못했습니다. (0) | 2023.04.02 |
Angular 1.5, 부모 컨트롤러에서 컴포넌트의 함수를 호출합니다. (0) | 2023.04.02 |