So as of Angular 1.1.4, you can have a dynamic template url. From here,
templateUrl - Same as template but the template is loaded from the specified URL
The following is also possible for creating dynamic templates in AngularJS: In your directive use:
template : '<div ng-include="getTemplateUrl()"></div>'
Now your controller may decide which template to use:
$scope.getTemplateUrl = function() {
return '/template/angular/search';
};
Because you have access to your scope parameters, you could also do:
$scope.getTemplateUrl = function() {
return '/template/angular/search/' + $scope.query;
};
So your server could create a dynamic template for you.
So the issue was with how I hacked the typeahead directive ... I was setting a scope variable on the typeahead, to be evaluated on the typeaheadPopup directive. Instead, I just passed the templateType attr directly as string & evaluated that. E.g.
var popUpEl = angular.element(
"<typeahead-popup " +
"matches='matches' " +
"active='activeIdx' " +
"select='select(activeIdx)' " +
"template-type='" + attrs.templateType + "'" +
"query='query' " +
"position='position'>" +
"</typeahead-popup>");
Instead of "template-type='templateType'"
Ran into a similar issue when creating a file upload fallback for browsers that don't support the File API (< IE10). Key difference is I needed the page to intelligently decide which template to display without the benefit of an attribute value to switch on.
I ended up using the constant provider for my directive. Constants basically set up default parameters that can be injected anywhere in your directive. I simply let the constant call a function to determine browser support, then reference that value when I need to determine which template to pull. This is nice since 1) there's no attribute to reference and 2) it's available during the pre-link phase when you don't have access to the controller.
(function () {
var myDir = angular.module('myDir', []);
myDir.constant('myDirConfig', {
hasFileSupport: fileApiIsSupported()
});
myDir.directive('myDir', ['myDirConfig', function (myDirConfig) {
return {
templateUrl: function () {
if (myDirConfig.hasFileSupport) {
return 'pathToTemplate/html5.html';
} else {
return 'pathToTemplate/fallback.html';
}
}
};
}];
function fileApiIsSupported() { return (...); }
})();
templateUrl: function (elem, attrs) {
return attrs["template"] == "table" ?
"tableTemplate.html" : "itemTemplate.html";
}