问题描述
我想显示使用指令从我的控制器对象的列表。里面的那个指令,我想能够使用几种可能的指令之一,但我不会总是知道哪一个。如果我在控制器的范围设置指令的名字,我怎么可以用它的主要指令的模板内?
I would like display a list of objects from my controller using a directive. Inside that directive I'd like to be able to use one of several possible directives, but I won't always know which one. If I set that directive name in the controller's scope, how can I use it within the template of the main directive?
下面是一个有什么下文。
Here's a plnkr with what's below.
HTML
<div ng-app="music" ng-controller="rock">
<h1>Favorite Bands</h1>
<prog></prog>
</div>
JS:
angular.module('music', []);
angular.module('music').controller('rock', ['$scope', function($scope){
$scope.directiveName = 'dinosaurs';
$scope.bands = [
{ name:'Rush'}, { name:'King Crimson' }, { name: 'Porcupine Tree'}, { name: 'Marillion'}];
}]);
angular.module('music').directive('prog', function(){
return {
restrict: 'E',
replace: true,
template: '<ul><li ng-repeat="band in bands"><{{directiveName}}>{{band.name}}</{{directiveName}}></li></ul>'
};
});
angular.module('music').directive('dinosaurs', function(){
return {
restrict: 'E',
transclude: true,
template: '<ng-transclude></ngtransclude> - DINOSAUR!'
};
});
在这种情况下,我设置 $ scope.directiveName
到恐龙
,这是名该指令我想主要的一个,叫 PROG
。
In this case, I'm setting the $scope.directiveName
to dinosaurs
, which is the name of the directive I want to use inside the main one, called prog
.
在 PROG
的模板,我试图用插插入指令的名字放到括号。然而,这本输出:
In prog
's template, I'm trying to use interpolation to insert the name of the directive into the brackets. That, however, outputs this:
- &LT;恐龙>拉什
- &LT;恐龙>国王深红
- &LT;恐龙>豪猪树
- &LT;恐龙>马里利恩
我也试过跨度使用类名:,和插入恐龙到跨度为一类,但角度不那么处理它作为指令
I've also tried using class name on a span: , and that inserts "dinosaurs" into the span as a class but Angular doesn't then process it as a directive.
我不知道如果我在这里需要一个隔离的范围,但是从我读过,我不认为这是相关的。我也新transclusion,但我认为恐龙
指令应采取每个列表项的内容,并添加! - 恐龙以它的结束。
I'm not sure if I need an isolate scope here, but from what I've read I don't think that's relevant. I'm also new to transclusion, but I think that the dinosaurs
directive should take the content of each list item and add " - DINOSAURS!" to the end of it.
什么是最好的实践方法去在一个指令的名称传递到另一个?
What's the best practice way to go about passing in the name of one directive to another?
推荐答案
我会做什么,以避免凌乱 $编译
s是使用纳克-include
作为开关,像
what I would do to avoid the messy $compile
s is use ng-include
as the switch, something like this:
angular.module('music').directive('prog', function(){
return {
restrict: 'E',
replace: true,
template: '<ul><li ng-repeat="band in bands"><div ng-include="directiveName + \'.html\'"></div></li></ul>'
};
});
这篇关于我可以使用其他指令内任意AngularJS指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!