【发布时间】:2014-11-07 20:13:30
【问题描述】:
我想使用指令显示来自我的控制器的对象列表。在该指令中,我希望能够使用几个可能的指令之一,但我并不总是知道是哪一个。如果我在控制器的范围内设置该指令名称,我如何在主指令的模板中使用它?
这是plnkr,下面是什么。
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 设置为dinosaurs,这是我想在主指令中使用的指令的名称,称为prog。
在prog 的模板中,我尝试使用插值将指令的名称插入括号中。然而,输出如下:
- 拉什
- 深红之王
- 豪猪树
- Marillion
我也尝试在 span: 上使用类名,并将“恐龙”作为一个类插入到 span 中,但 Angular 不会将其作为指令处理。
我不确定我是否需要隔离范围,但从我所读到的内容来看,我认为这无关紧要。我也是嵌入的新手,但我认为dinosaurs 指令应该获取每个列表项的内容并添加“ - DINOSAURS!”到最后。
将一个指令的名称传递给另一个指令的最佳实践方法是什么?
【问题讨论】:
-
我一直在关注docs.angularjs.org/guide/directive 和Dan Wahlin's posts on directives。几个主题,如this one 地址指令在其他指令中,但不传递这些指令的名称。
-
如果你先声明恐龙指令,有帮助吗?
-
@dandavis - 不错的想法,但显然不是。我在 plnkr 上试过了,但没有运气。
-
可以使用链接功能连接到父指令控制器-
function(scope, el, attr, ctrl)
标签: javascript angularjs