TL; DR:有没有办法根据参数值动态设置指令?类似于ng-class
用于设置css元素的东西,但是一种基于范围中的值设置指令的方法。我会在范围内获得价值所以我可以打电话:
<div class="data.directiveType"></div>
当
data.directiveType = "my-directive"
<div class="my-directive"></div>
和myDirective会被调用吗?
详细问题:
我想要做的是允许用户向Web应用程序添加元素,我希望根据用户点击的内容添加每个元素的指令。
我有以下指令:
app.directive("mySuperman", function(){
//directive logic
});
app.directive("myBatman", function(){
//directive logic
});
app.directive("myWonderWoman", function(){
//directive logic
});
我有以下控制器
app.controller("ParentCtrl", function($scope){
$scope.superHeros = [];
var superman = {directiveType: "my-superman"};
var batman = {directiveType: "my-batman"};
var wonderWoman = {directiveType: "my-wonder-woman"}
$scope.addBatman = function()
{
var batmanInstance = {}
angular.copy(batman, batmanInstance);
$scope.superHeros.push(batmanInstance);
}
$scope.addSuperman = function()
{
var supermanInstance = {}
angular.copy(superman, supermanInstance);
$scope.superHeros.push(supermanInstance);
}
$scope.addWonderWoman = function()
{
var wonderwomanInstance = {}
angular.copy(wonderWoman, wonderwomanInstance);
$scope.superHeros.push(wonderwomanInstance);
}
});
在index.html中我有
<body ng-controller="ParentCtrl>
<a ng-click="addBatman()">Add Batman</a>
<a ng-click="addSuperman()">Add Superman</a>
<a ng-click="addWonderWoman()">Add WonderWoman</a>
<div ng-repeat="hero in superHeros">
<!-- The following doesn't work, but it is the functionality I am trying to achieve -->
<div class={{hero.directiveType}}></div>
<div>
</body>
我想到这样做的另一种方式就是在ng-include
中使用ng-repeat
并将模板url添加到hero
对象而不是指令类型,但我希望在那里是一种更清洁的方式,我可以更好地利用数据绑定,而不必只是调用ng-include
来调用另一个指令。
答案 0 :(得分:3)
您可以创建一个指令,该指令将指令作为参数添加,将其添加到元素并进行编译。然后像这样使用它:
<div ng-repeat="hero in superHeros">
<div add-directive="hero.directiveType"></div>
</div>
这是一个基本的例子:
app.directive('addDirective', function($parse, $compile) {
return {
compile: function compile(tElement, tAttrs) {
var directiveGetter = $parse(tAttrs.addDirective);
return function postLink(scope, element) {
element.removeAttr('add-directive');
var directive = directiveGetter(scope);
element.attr(directive, '');
$compile(element)(scope);
};
}
};
});