[英]angular dynamic templating directives
我有一个不同字段类型的列表,我想根据类型应用模板。 如果使用如下内联模板,则可以使其正常工作:
flowPageModule.directive('myField', ['$compile','$http', '$templateCache', function($compile, $http, $templateCache) {
var inlineTemplateMapping = {
select: '<div><span> {{label}}   <select ng-model="metadata.options[0]" ng-options="o.text for o in metadata.options"></select> </span></div>',
text: '<div><span> {{label}}   <input type="text" /> </span></div>'
}
return {
restrict: 'E',
replace: true,
transclude: true,
scope: { type: '=', label: '=', metadata: '=' },
link: function (scope, element, attrs) {
if (scope.metadata) { alert(scope.metadata.options[0].text); }
var templateLiteral = inlineTemplateMapping[scope.type];
element.html(templateLiteral);
$compile(element.contents())(scope);
}
};
}]);
如果可以使用$ http服务从文件中检索模板,我真的希望它能够正常工作。 我尝试了下面的内容,但始终收到Type错误。
flowPageModule.directive('myField', ['$compile','$http', '$templateCache', function($compile, $http, $templateCache) {
var baseUrl = 'directives/field/',
typeTemplateMapping = {
text: 'my-field-text.html',
select: 'my-field-select.html'
};
return {
restrict: 'E',
replace: true,
transclude: true,
scope: { type: '=', label: '=', metadata: '=' },
link: function (scope, element, attrs) {
var templateUrl = baseUrl + typeTemplateMapping[scope.type];
$http.get(templateUrl, {cache: $templateCache}).success( function(html) {
element.html();
$compile(element.contents())(scope);
});
}
};
}]);
为什么会这样?
我为此创造了报酬,但是由于实际上没有人真正在乎实现(好还是坏?)……我可以随时与社区分享此信息。 我从另一个SO答案改编了loadT()函数。 您可以找到它搜索“动态模板角度”。 此处的调整允许您在$ http promise没有返回的情况下显示一个空组件。
用法
<p dynamic template="'template/file.html'"></p>
<p dynamic template="someObjectInController.value"></p>
*包含无效。 因此,随时添加/更正。 问题在于缺少有关transclude函数的文档。
cpanel.directive("dynamic", ["$compile", '$templateCache', '$http',
function ($compile, $templateCache, $http) {
return {
priority: 0,
restrict: 'EA',
replace: true,
transclude: true,
controller: 'SomeController',
scope: {
template: "@template"
},
link: function (scope, iElement, iAttrs) {
scope.$parent.$watch(iAttrs.template, function (newvalue, oldvalue) {
if ((oldvalue !== newvalue) && (newvalue !== undefined) && (newvalue !== null)) {
loadT(newvalue);
} else if ((newvalue !== undefined) && (newvalue !== null)) {
loadT(newvalue);
} else {
//TODO
}
}, true);
function loadT(it) {
$http.get(it, { cache: $templateCache}).success(function (templateContent) {
iElement.replaceWith($compile(templateContent)(scope));
});
}
}
};
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.