我一直在使用 $compile 服务来动态注入(inject)一个元素,但被一些意想不到的事情打败了。所以,这是我以前注入(inject)指令的方式:
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)
})
在此fiddle ,你可以看到该指令似乎被编译了两次。所以我删除了 $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>')
})
那么,.append
是编译指令吗?
我有点困惑,因为我一直将第一个版本视为推荐版本,但我在 jqLike 的“追加”实现中找不到任何与编译相关的内容。
最佳答案
这是因为 run
阶段发生在 DOM 第一次编译之前。它与使用 append()
此用例不需要您在 run()
中使用的 $compile
。
关于javascript - Angular 在使用 jq append 方法时是否编译指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35893643/