seyid yagmur seyid yagmur - 3 months ago 9
Javascript Question

Creating item dynamically in controller with AngularJS

I created a custom directive like below.

app.directive('myDirective', function () {
return {
template: '<h1>This is myDirective</h1>',
restrict: 'E',
replace: true,
link: function (scope, element, attrs) {

}
};
});


and my HTML code is like below.

<ion-view view-title="Search">
<ion-content>
<div id="myid"></div>
</ion-content>
</ion-view>


Finally, my controller is like below. I would like to create
my-directive
element dynamically inside the controller like below. But it doesn't work. Do you know any way to solve this problem?
thanks in advance!!

app.controller('Search', function ($scope) {
var content = document.getElementById("myid");
content.setAttribute("class", "list");
var mydir = document.createElement("my-directive");

content.appendChild(mydir);
})

Answer

Not sure what is the reason behind this:

my template data coming from server dynamicly and using inside the controller is the best solution for me

Well, it is not recommended but yes, you can do it. See an example below:

var app = angular.module("sa", []);

app.controller("Search", function($scope, $compile) {

  $scope.doTheBadThing = function() {
    var $parent = angular.element(document.getElementById("myid"));
    $parent.addClass("list");
    var mydir = document.createElement("my-directive");
    // or
    //var mydir = "<my-directive></my-directive>"; 
    $parent.append(mydir);

    // This is the main thing. You need to compile the dynamic HTML so that Angular can initialized on those template
    $compile($parent.contents())($scope);
  };
});

app.directive('myDirective', function() {
  return {
    template: '<h1>This is myDirective</h1>',
    restrict: 'E',
    replace: true,
    link: function(scope, element, attrs) {

    }
  };
});
#myid {
  background: #ccc;
  min-height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="Search">
  <button ng-click="doTheBadThing()">Do the bad thing</button>
  <div id="myid"></div>
</div>