Angular 在使用 jq 追加方法时是否编译指令

Is Angular compiling a directive when using the jq append method?

本文关键字:是否 编译 指令 方法 追加 jq Angular      更新时间:2023-09-26

我一直在使用$compile服务来动态注入元素,但只是被一些意想不到的东西打败了。所以,这是我过去注入指令的方式:

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)
    })

在这个小提琴中,您可以看到该指令似乎被编译了两次。所以我删除了$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 的"append"实现中找不到与编译相关的任何内容。

这是因为run阶段发生在第一次编译 DOM 之前。它与使用append()

无关

此用例不需要您在run()中使用的$compile