Javascript 使用JQAppend方法时,Angular编译是一个指令吗?
我一直在使用$compile服务来动态注入元素,但却被一些意想不到的事情打败了。下面是我如何注入指令的:Javascript 使用JQAppend方法时,Angular编译是一个指令吗?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我一直在使用$compile服务来动态注入元素,但却被一些意想不到的事情打败了。下面是我如何注入指令的: angular .module('app', []) .directive('test', function () { return { restrict: 'E', controller: function () { console.log('hey, just got comp
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)
})
angular
.module('应用程序',[])
.directive('test',function(){
返回{
限制:'E',
控制器:函数(){
log('嘿,刚刚编译好!')
}
}
})
.run(函数($compile,$rootScope){
var$scope=$rootScope.$new()
var指令=$compile(“”)($scope)
var app=angular.element(document.querySelector(“[ng app]”)
app.append(指令)
})
在这里,您可以看到指令似乎被编译了两次。因此,我删除了$compile技巧,它工作正常,指令编译一次:
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>')
})
angular
.module('应用程序',[])
.directive('test',function(){
返回{
限制:'E',
控制器:函数(){
log('嘿,刚刚编译好!')
}
}
})
.run(函数($compile,$rootScope){
var app=angular.element(document.querySelector(“[ng app]”)
app.append(“”)
})
那么,.append
是否正在编译指令
我有点困惑,因为我一直认为第一个版本是推荐的版本,在jqLike的“append”实现中找不到任何与编译相关的内容。这是因为
运行阶段发生在第一次编译DOM之前。它与使用append()
此用例不需要在run()
中使用的$compile
非常感谢,这很有道理!虽然我找不到angular的运行周期的详细文档,但我发现这个答案特别有趣:与其使用querySelector
查找$rootElement
,不如插入$rootElement
并附加到它。@georgeawg谢谢,太好了!