After doing some search I haven't found much information in this bad practice. Let's say I have a controller that behaves like that (I know it should have been a directive and that in controllers we never do DOM manipulation but I am curious..)
angular.module('app').controller('test', ['$scope',
function($scope) {
$scope.addElement = function() {
var input = document.createElement('input');
input.type = "text";
//directive
input.setAttribute("autosize","autosize");
input.setAttribute("ng-model","dummy");
//[ append code ]
input.focus();
}
}
]);
and let's assume that I have a button that triggers addElement() with ng-click. How the existing autosize directive will be "triggered" to actually work. In contrast input elements that preexist and have the autosize directive work fine. I also tried $scope.apply(function() { }); around the indented code that creates the input element and it causes TypeError: undefined is not a function :/
Based on Mohammad Shahrouri's comment above, I had to inject the $compile
dependency in the controller and I had to add $compile(input)($scope);
at the end:
angular.module('app').controller('test', ['$scope','$compile',
function($scope, $compile) {
$scope.addElement = function() {
var input = document.createElement('input');
input.type = "text";
//contains directive
input.setAttribute("autosize","autosize");
input.setAttribute("ng-model","dummy");
//[ append code ]
input.focus();
$compile(input)($scope);
}
}
]);
来源:https://stackoverflow.com/questions/26447885/how-directives-are-invoked-if-an-element-that-contains-a-directive-is-added-dyna