dyrektywy dynamicznych szablonów kątowych
Mam listę różnych typów pól i chcę zastosować szablon na podstawie typu. Mogę go uruchomić, jeśli korzystam z takich szablonów:
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);
}
};
}]);
Naprawdę chciałbym, żeby działało, gdybym mógł użyć usługi $ http, aby pobrać szablon z pliku. Próbowałem tego, co jest poniżej, ale zawsze otrzymuję błąd typu.
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);
});
}
};
}]);
Dlaczego to się dzieje?