1

I am trying add HTML elements through javascript that has a directive:

document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>";
or
var ele = document.createElement("div");
ele.setAttribute("ng-uc-day-event","");
document.getElementsByClassName("day-grid")[0].appendChild(ele);

Both results in adding the div to .day-grid. I am using a directive to load template from an external file into ng-uc-day-event. It works as expected when it is run from the HTML file, but it doesn't work when I run the above code from the developer console.

How do I make angularjs to call the directive or evaluate the element when I am adding the element to DOM, so that the template is loaded into div when it is inserted into .day-grid?

Below is the directive I am using:

ulcal.directive("ngUcDayEvent", function ($timeout) {
  return {
    restrict: 'A',
    templateUrl: 'views/dayevent.html',
    link: function (s, e, a) {
      $timeout(function () {
        s.$emit("ucDayEventLoaded");
      })
    }
  }
});
2
  • possible duplicate stackoverflow.com/questions/26447885/… Commented Oct 27, 2014 at 4:00
  • @MichailMichailidis That question is for adding the element from the controller. I know how to do that. What I want to know is how to add an element completely from outside, eg: through jquery, dev console etc. Any way that link too helped me. Thank you Commented Mar 21, 2015 at 0:52

2 Answers 2

2

You need to tell Angular to $compile the template and associate it with a scope. Angular will not recognise bits of HTML being inserted into the DOM at arbitrary times.

Inject the $compile service to wherever you are doing your DOM manipulation.

var container = angular.element(document.getElementsByClassName('day-grid')[0]);
var myDirective = angular.element('<div ng-uc-day-event></div>');

container.append(myDirective);

$compile(container)(scope);
Sign up to request clarification or add additional context in comments.

1 Comment

This is similar to adding the element from the controller: stackoverflow.com/questions/26447885/…. I know how to do that. What I want to know is how to add an element completely from outside, eg: through jquery, dev console etc. Any way your answer also helped me. Thank you
1

This solved my problem:

inj = angular.injector(['ng', ApplicationName]);
inj.invoke(function ($rootScope, $compile) {
   ele = $compile("<div ng-uc-day-event></div>")($rootScope)[0];
   $(".day-grid").append(ele);
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.