I've always been using the $compile service to dynamically inject an element but just got beaten by something unexpected. So, here is how I used to inject a directive:
angular
.module('app', [])
.directive('test', function () {
return {
restrict: 'E',
controller: function () {
console.log('hey, just got compiled!')
}
}
})
.run(function ($compile, $rootScope) {
var $scope = $rootScope.$new()
var directive = $compile('<test></test>')($scope)
var app = angular.element(document.querySelector('[ng-app]'))
app.append(directive)
})
In this fiddle, you can see that the directive seems to be compiled twice. So I removed the $compile trick and it's working just fine, the directive is compiled once:
angular
.module('app', [])
.directive('test', function () {
return {
restrict: 'E',
controller: function () {
console.log('hey, just got compiled!')
}
}
})
.run(function ($compile, $rootScope) {
var app = angular.element(document.querySelector('[ng-app]'))
app.append('<test></test>')
})
So, is .append
compiling the directive?
I am a bit confused as I've always seen the first version as the recommended one and I can't find anything related to compilation in the jqLike's implementation of "append".