0

I am new to angularjs. I want to dynamically add directives to a div based the titles from controller.. Below is what i tried...

Below is the directives and factory i used

     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'
    }   
  })

Below is how i use ng-repeat

<div ng-repeat="Questions in Questions" >
    <div dynamicDirective="{{Questions.title}}"  ></div>
</div>

This is not working

bharath
  • 755
  • 2
  • 10
  • 19

3 Answers3

3

use-kebab-case-in-html

<div ng-repeat="Question in Questions" >
    <div dynamic-directive="{{Question.title}}"  ></div>
</div>
Sr.Richie
  • 5,480
  • 4
  • 34
  • 61
maurycy
  • 8,393
  • 1
  • 25
  • 42
2

You need to write dynamic-directive instead of dynamicDirective in your HTML. Camelcase in Javascript needs to be written as snakecase kebab-case in HTML.

ilmgb
  • 780
  • 4
  • 20
  • I just learned that snake case is this "dynamic_directive" (an underscore as separator). As @maurycy mentioned it is called kebab-case. See: http://stackoverflow.com/questions/11273282/whats-the-name-for-dash-seperated-case – ilmgb Jul 06 '15 at 11:05
0

Here you are:

<div ng-repeat="Question in Questions" >
    <div dynamicDirective="{{Question.title}}"  ></div>
</div>

Hope this helps.

hungndv
  • 1,931
  • 1
  • 14
  • 19