为此,您的模板必须首先在作用域上编译和执行(以替换 {{baz}}),然后再次编译并执行以使“foo-thing”指令运行。这是可能的,但它可能会导致其他问题。
你可以做的是创建一种指令工厂,一个创建另一个指令的指令。这是一个例子:
<!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>