It seems like there is an issue with this code:
var run_div = document.createElement('div');
run_div.className = 'whatever';
run_div.textContent = 'whatever';
run_div.setAttribute('ng-mouseover', 'console.log(\'ei\')');
document.getElementById('main_div').appendChild(run_div);
I believe the problem arises because ng-mouseover
needs to be present from the beginning for AngularJS to recognize it (?).
Is this correct? Is there a workaround?
(below: UPDATE 1, UPDATE 2, UPDATE 3)
UPDATE 1:
This code functions in a factory, where I invoke the factory method from the controller passing it the $scope
:
angular.module('whatever').controller('mycontroller',
['$scope', '$q', '$window', '$timeout',
function ($scope, $q, $window, $timeout) {
$scope.myfunction= function() {
myfactory.mymethod($scope);
};
The factory invokes the $compile
within its definition:
angular.module('whatever').factory('myfactory',
['$window', '$q', '$compile',
function($window, $q, $compile) {
...
mymethod = function($scope) {
var run_div = document.createElement('div');
run_div.className = 'whatever';
run_div.textContent = 'whatever';
run_div.setAttribute('ng-mouseover', 'console.log(\'ei\')');
document.getElementById('main_div').appendChild(run_div);
}
This approach does not work, leading to an error:
document.getElementById('main_div').appendChild($compile(run_div)($scope));
document.getElementById('main_div').appendChild($compile(run_div)($scope.new()));
or even:
var run_div = angular.element(document.createElement('div'));
run_div.addClass('whatever');
run_div.attr('ng-mouseenter', 'console.log(\'ei\'');
document.getElementById('main_div').appendChild($compile(run_div)($scope));
An error message indicates that the parameter being appended is not a node.
Uncaught (in promise) TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.(…)
UPDATE 2:
Evidence suggests that compiling and appending from a factory does not work, but from a controller it does (refer to answer 2):
http://jsfiddle.net/xsaudasp/1/
UPDATE 3
As demonstrated here, it should work: