我有一个不同字段类型的列表,我想根据类型应用一个模板。如果我像这样使用内联模板,我可以让它工作:
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服务从文件中检索模板,我真的希望它能正常工作。我已经尝试了下面的方法,但我总是得到一个类型错误。
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);
});
}
};}]);
这一切为什么要发生?
发布于 2013-12-20 23:16:36
我得到了创建这个的报酬,但是因为实际上没有人真正关心它的实现(好的还是坏的?)...I我觉得可以自由地将它分享给社区。我从另一个SO答案中修改了loadT()函数。你可以搜索"dynamic template angular“找到它。这里的调整允许您在$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));
});
}
}
};
}
]);https://stackoverflow.com/questions/19944036
复制相似问题