I have two class-restricted directives, named fooThing and barThing.
I have a variable, baz, in my template scope that is set to either foo or bar.
How can I use that scope variable in the name of the directive for an element?
When I do <div class="{{baz}}-thing"></div>, {{baz}} is replaced properly, but the directive is not loaded.
When I do <div class="foo-thing"></div>, the directive is loaded properly.
I have a hunch that this has something to do with Angular's digest/compile cycle, but I'm afraid I don't know how to work around it.
How can I get Angular to compile that part of the template first so that my expression is evaluated, and then have it compile again so it recognizes it as a directive?
For that to work your template would have to first be compiled and executed on a scope (to replace {{baz}}), and then compiled and executed again to get the "foo-thing" directive going. It's possible, but it would probably cause other issues.
What you could do is create sort of a directive factory, a directive that creates another directive. Here's an example:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module("myApp", []);
myApp.directive('factory', function($compile) {
return {
restrict: 'A',
scope: {
type: '=factory'
},
replace: true,
link: function($scope, elem, attrs) {
var compiled = $compile('<'+ $scope.type +'></'+ $scope.type +'>')($scope);
elem.append(compiled);
}
};
});
myApp.directive('concrete', function() {
return {
restrict: 'E',
template: "<div>I'm concrete!</div>",
link: function($scope, elem, attrs) {
}
};
});
function MyCtrl($scope, $timeout) {
$scope.directiveType = "concrete";
}
</script>
</head>
<body>
<div ng-controller="MyCtrl">
<div factory="directiveType"></div>
</div>
</body>
</html>
Making a directive that creates directives (a kind of directive factory), as suggested by Anders, is what I'm after. Guillaume86 provided a good method for doing that.