2

I'm trying to generated multiple div dynamically but adding a ng-click attribute doesn't work.

Here's my code

        var div = document.createElement('DIV');
        div.className = 'container-car';

        var child_div = document.createElement('DIV');
        child_div.className = 'carre-car';
        child_div.setAttribute("ng-click", "$scope.testCharacter(" + JSON.stringify(unicode) + ")");

        var child_paragraphe = document.createElement('P');
        var child_text = document.createTextNode($scope.unicode_from_int(unicode['unicode']));
        child_paragraphe.appendChild(child_text);

        child_div.appendChild(child_paragraphe);

        div.appendChild(child_div);

        var paragraphe = document.createElement('P');
        var text = document.createTextNode(unicode['pinyin']);
        paragraphe.appendChild(text);

        div.appendChild(paragraphe);

        document.getElementById('container-biblio').appendChild(div);

I tried another way like shown in this post but it doesn't seems to work.

Community
  • 1
  • 1
plean
  • 124
  • 1
  • 9
  • You are just keep adding DOM, you have to compile a DOM with `$compile` service to make binding enable on DOM – Pankaj Parkar Dec 09 '16 at 21:31
  • @PankajParkar you mean something like `$compile(child_div)($scope);` after the `child_div.setAttribute("ng-click",...` line ? – plean Dec 09 '16 at 21:38

1 Answers1

1

Try this:

var div = document.createElement('DIV');
div.className = 'container-car';

var child_div = document.createElement('DIV');
child_div.className = 'carre-car';
child_div.setAttribute("ng-click", "testCharacter(" + JSON.stringify(unicode) + ")");

var child_paragraphe = document.createElement('P');
var child_text = document.createTextNode($scope.unicode_from_int(unicode['unicode']));
child_paragraphe.appendChild(child_text);

child_div.appendChild(child_paragraphe);

$compile(child_div)($scope);

div.appendChild(child_div);

var paragraphe = document.createElement('P');
var text = document.createTextNode(unicode['pinyin']);
paragraphe.appendChild(text);

div.appendChild(paragraphe);

document.getElementById('container-biblio').appendChild(div);

You don't need to use $scope in your case and you forgot to $compile(child_div)($scope); to let angular interpret your angularjs specific attributes.

LazyShpee
  • 82
  • 12