AngularJS에서 동적 템플릿을 사용하여 디렉티브를 작성하려면 어떻게 해야 합니까?
다이내믹 템플릿을 사용하여 디렉티브를 작성하려면 어떻게 해야 합니까?
'use strict';
app.directive('ngFormField', function($compile) {
return {
transclude: true,
scope: {
label: '@'
},
template: '<label for="user_email">{{label}}</label>',
// append
replace: true,
// attribute restriction
restrict: 'E',
// linking method
link: function($scope, element, attrs) {
switch (attrs['type']) {
case "text":
// append input field to "template"
case "select":
// append select dropdown to "template"
}
}
}
});
<ng-form-field label="First Name" type="text"></ng-form-field>
지금 가지고 있는 것은 이것이며, 라벨은 올바르게 표시되어 있습니다.그러나 HTML을 템플릿에 추가하는 방법을 잘 모르겠습니다.또는 두 개의 템플릿을 하나로 결합할 수도 있습니다.
$templateCache를 사용하여 비슷한 작업을 수행했습니다.하나의 html 파일에 여러 개의 ng-template를 저장하여 디렉티브의 templateUrl을 사용하여 참조합니다.이것에 의해 html이 템플릿 캐시에서 사용 가능하게 됩니다.그럼 아이디로 선택해서 내가 원하는 ng-module을 얻을 수 있어.
template.template:
<script type="text/ng-template" id=“foo”>
foo
</script>
<script type="text/ng-template" id=“bar”>
bar
</script>
지시:
myapp.directive(‘foobardirective’, ['$compile', '$templateCache', function ($compile, $templateCache) {
var getTemplate = function(data) {
// use data to determine which template to use
var templateid = 'foo';
var template = $templateCache.get(templateid);
return template;
}
return {
templateUrl: 'views/partials/template.html',
scope: {data: '='},
restrict: 'E',
link: function(scope, element) {
var template = getTemplate(scope.data);
element.html(template);
$compile(element.contents())(scope);
}
};
}]);
비슷한 욕구가 있었다. $compile
그 일을 해냅니다.(이게 'THE' 방식인지 잘 모르겠지만, 여전히 각을 그리며 내 방식대로 해나가고 있다.
http://jsbin.com/ebuhuv/7/edit - 내 탐사 테스트
한 가지 주의할 점은 (이 예에 따라) 템플릿이 변경된다는 것입니다.type
[저장(Save)]버튼을 클릭하면 템플릿이 많이 다릅니다.따라서 데이터 바인딩이 있지만 새 템플릿이 필요한 경우 다시 컴파일해야 합니다.
ng-switch 명령을 사용하여 스위치를 템플릿으로 이동해야 합니다.
module.directive('testForm', function() {
return {
restrict: 'E',
controllerAs: 'form',
controller: function ($scope) {
console.log("Form controller initialization");
var self = this;
this.fields = {};
this.addField = function(field) {
console.log("New field: ", field);
self.fields[field.name] = field;
};
}
}
});
module.directive('formField', function () {
return {
require: "^testForm",
template:
'<div ng-switch="field.fieldType">' +
' <span>{{title}}:</span>' +
' <input' +
' ng-switch-when="text"' +
' name="{{field.name}}"' +
' type="text"' +
' ng-model="field.value"' +
' />' +
' <select' +
' ng-switch-when="select"' +
' name="{{field.name}}"' +
' ng-model="field.value"' +
' ng-options="option for option in options">' +
' <option value=""></option>' +
' </select>' +
'</div>',
restrict: 'E',
replace: true,
scope: {
fieldType: "@",
title: "@",
name: "@",
value: "@",
options: "=",
},
link: function($scope, $element, $attrs, form) {
$scope.field = $scope;
form.addField($scope);
}
};
});
다음과 같이 사용할 수 있습니다.
<test-form>
<div>
User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}
</div>
<form-field title="Email" name="email" field-type="text" value="me@example.com"></form-field>
<form-field title="Role" name="role" field-type="select" options="['Cook', 'Eater']"></form-field>
<form-field title="Sex" name="sex" field-type="select" options="['Awesome', 'So-so', 'awful']"></form-field>
</test-form>
지시문에서 템플릿 함수를 사용하는 것도 한 가지 방법입니다.
...
template: function(tElem, tAttrs){
return '<div ng-include="' + tAttrs.template + '" />';
}
...
If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.
I managed to deal with this problem. Below is the link :
https://github.com/nakosung/ng-dynamic-template-example
with the specific file being:
https://github.com/nakosung/ng-dynamic-template-example/blob/master/src/main.coffee
dynamicTemplate
directive hosts dynamic template는 범위 내에서 전달되며 호스트 요소는 다른 네이티브 각도 요소와 동일하게 작동합니다.
scope.template = '< div ng-controller="SomeUberCtrl">rocks< /div>'
I have been in the same situation, my complete solution has been posted here
Basically I load a template in the directive in this way
var tpl = '' +
<div ng-if="maxLength"
ng-include="\'length.tpl.html\'">
</div>' +
'<div ng-if="required"
ng-include="\'required.tpl.html\'">
</div>';
의 가치에 따라maxLength
그리고.required
2개의 템플릿 중 하나를 동적으로 로드할 수 있습니다.필요에 따라 한 번에 1개만 표시됩니다.
I heope it helps.
ReferenceURL : https://stackoverflow.com/questions/14862315/how-to-create-a-directive-with-a-dynamic-template-in-angularjs
'programing' 카테고리의 다른 글
리액트 라우터에서 이전 경로를 검출하시겠습니까? (0) | 2023.03.03 |
---|---|
트랜스코프된 디렉티브의 부모 스코프 액세스 (0) | 2023.03.03 |
MUI를 사용하는 CSS 의사 실렉터 (0) | 2023.03.03 |
콘텐츠 유형 'contentart/form-data;content=-----...;charset=UTF-8'은 지원되지 않습니다. (0) | 2023.02.26 |
spread 연산자 vs array.concat() (0) | 2023.02.26 |