扩展@goofy 的答案并回答@ironic,这是我想出的:
(function (angular) {
var messageSelectorDirective = ['$compile', function ($compile) {
// Create cached message templates, this could also come from a service or you can use other caching strategies
var messageTypeTemplates = {
'TYPE1': $compile('<message-type1 class="message" />'),
'IMAGE': $compile('<image-message class="message image-message" maybe-another-directive />'),
'SMS_FOLLOWUP': $compile('<sms-message class="message message-type3" ng-hide="thisCanWorkToo" />'),
'DEFAULT': $compile('<message-type1 class="message" />')
};
// Based on the supplied message.$type property, select an appropriate directive -- returns a default if not found
function getCompiledMessageTemplate(message) {
return angular.isDefined(messageTypeTemplates[message.$type]) ? messageTypeTemplates[message.$type] : messageTypeTemplates['DEFAULT'];
}
return {
restrict: 'A',
scope: {
$message: '=message',
$context: '=context'
// You could also provide a selector function here that determines how to choose a directive from the message, or it could be a service ...
},
link: function (scope, element) {
var template = getCompiledMessageTemplate(scope.$message);
var templateElement;
template(scope, function (clonedElement, scope) {
templateElement = clonedElement;
element.append(templateElement);
});
template = null;
element.on("$destroy", function () {
templateElement.remove();
templateElement = null;
});
}
// You can optionally have a controller here that allows you operate on the supplied context since this is an isolated directive
// controller: 'MessageSelectorController'
};
}];
angular.module('directives').directive('messageSelector', messageSelectorDirective);
})(angular);
在 HTML 中的用法:
...
<ol class="list-unstyled">
<li class="row" message-selector message="::message" context="::context" ng-repeat="message in filteredMessages = (messages | limitLast:renderLimit) track by message.id">
<!--
In here will be the properly selected directive rendered according the the message.$type. When you receive the data from the server, you can
decide how to map an individual message in to a given $type which the directive above will use, OR, you can use another strategy for selection!
Since you have full control over the template selection, you can also decide what things you want to be in an individual message. You have lots of options here!
-->
</li>
</ol>
...
希望这可以帮助某人或提供一些想法!