I have a list of different field types and I want to apply a template based on type. I can get it to work if I use inline templates like this:
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);
}
};
}]);
I would really like for it to work if i could use the $http service to retrieve a template from a file. I have tried what is below, but I always get a Type error.
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);
});
}
};
}]);
Why does this happen?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…