我是angularjs的新手。我想根据控制器的标题动态地将指令添加到div中。以下是我尝试的...
以下是我使用的指令和工厂
QtTemplate.directive("shortanswer",function()
{
return{
restrict:"A",
templateUrl:'assets/directives/shortAnswer.html'
}
})
Template.factory("questionList",function()
{
var questionList={};
questionList.testid="1";
questionList.name="Maths";
questionList.Questions =
[
{"title":"truefalse"},
{"title":"shortanswer"}
]
return questionList;
})
Template.controller("questionControl",['$scope','questionList',function($scope,questionList)
{
$scope.name = questionList.name;
$scope.id = questionList.testid;
$scope.Questions = questionList.Questions;
}])
Template.directive('dynamicDirective',function($compile)
{
return {
restrict: 'A',scope:{},
replace: false,
terminal: true,
priority: 1000,
link:function(scope,element,attrs)
{
element.attr(scope.$eval(attrs.dynamicDirective),"");
element.removeAttr("dynamic-directive"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-dynamic-directive");
$compile(element)(scope);
}
};
});
QtTemplate.directive("shortanswer",function()
{
return{
restrict:"A",
templateUrl:'assets/directives/shortAnswer.html'
}
})
以下是我如何使用ng-repeat
<div ng-repeat="Questions in Questions" >
<div dynamicDirective="{{Questions.title}}" ></div>
</div>
这不起作用
答案 0 :(得分:3)
使用-串的病例中,HTML
<div ng-repeat="Question in Questions" >
<div dynamic-directive="{{Question.title}}" ></div>
</div>
答案 1 :(得分:2)
您需要在HTML中编写dynamic-directive
而不是dynamicDirective
。 Javascript中的Camelcase需要用HTML编写为 snakecase kebab-case。
答案 2 :(得分:0)
你在这里:
<div ng-repeat="Question in Questions" >
<div dynamicDirective="{{Question.title}}" ></div>
</div>
希望这有帮助。