如何通过 jQuery 的 .append() 添加 DOM 元素(Angular 指令)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20059231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:56:24  来源:igfitidea点击:

How to add DOM Elements (Angular directives) via jQuery's .append()?

jqueryangularjs

提问by blaster

Is there any way to add an element that is an Angular directive with jQuery methods like append()and have Angular do its compilation/linking to make it work as though you'd included the directive in the first place?

有什么方法可以使用 jQuery 方法添加 Angular 指令的元素,append()并让 Angular 进行编译/链接以使其工作,就像您首先包含该指令一样?

Example:

例子:

app.directive('myAngularDirective', [function () {
    ...
    // Lots of stuff in here; works when used normally but not when added via jQuery
});

$("body").append("<my-angular-directive />");

It currently just appends an empty DOM element called "my-angular-directive," but Angular doesn't kick in and do its magic.

它目前只是附加一个名为“my-angular-directive”的空 DOM 元素,但 Angular 并没有发挥作用。

回答by artur grzesiak

The right way to go is to use: $compileand in case your directive returns: directive definition object(which is btw. the recommended way to go) you can then call linkfunction on it (to inject scope, for example).

正确的方法是使用:$compile,如果你的指令返回:(directive definition object顺便说一句。推荐的方法)然后你可以调用link它的函数(scope例如注入)。

$('body').append($compile("<my-angular-directive />")(scope));
scope.$apply(); 

回答by David Wolever

A complete example, from the Angular documentation:

一个完整的例子,来自Angular 文档

// Angular boilerplate
var app = angular.module("myApp", []);
app.controller("MyCtrl", function($scope) {
  $scope.content = {
    label: "hello, world!",
  };
});

// Wrap the example in a timeout so it doesn't get executed when Angular
// is first started.
setTimeout(function() {
  // The new element to be added
  var $div = $("<div ng-controller='MyCtrl'>new: {{content.label}}</div>");
  
  // The parent of the new element
  var $target = $("[ng-app]");

  angular.element($target).injector().invoke(function($compile) {
    var $scope = angular.element($target).scope();
    $target.append($compile($div)($scope));
    // Finally, refresh the watch expressions in the new element
    $scope.$apply();
  });
}, 100);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="myApp">
   <div ng-controller="MyCtrl">old: {{content.label}}</div>
</div>

回答by ilovelamp

The accepted answer didn't provide a complete example, here's one:

接受的答案没有提供完整的例子,这是一个:

https://codepen.io/rhinojosahdz/pen/ZpGLZG

https://codepen.io/rhinojosahdz/pen/ZpGLZG

<body ng-app="app" ng-controller="Ctrl1 as ctrl1">
</body>
<script>
angular.module('app',[])
.controller('Ctrl1', ['$scope', '$compile', function($scope, $compile){
    var vm = this;
    vm.x = 123;
    $('body').append($compile("<hola x='ctrl1.x' />")($scope));
}])
.directive('hola', function(){
    return {
        template: '<div ng-click="vm.alertXFromGivenScope()">click me!</div>'
        ,scope: {
            x : '='
        }
        ,controller: function(){
            var vm = this;
            vm.alertXFromGivenScope = function(){
                alert(vm.x);                
            };
        }
        ,controllerAs: 'vm'
        ,bindToController: true
    }
})
<script>

回答by musically_ut

Ideally you should avoid doing that.

理想情况下,您应该避免这样做。

However, if you really, really, reallyneed to, then you can inject and use the $compileservicefollowed by an element.append.

但是,如果你真的,真的,真的需要,那么你可以注入,并使用$compile服务后跟element.append

If your directivedoesn't need access to a specific scope, then you can even assign the $compileand $rootScopeservice to windowin the runfunction of your application's module and then use them from outside the angular context by creating a new scope($rootScope.new()) and wrap the appending of element by using $rootScope.apply().

如果您的指令不需要访问特定范围,那么您甚至可以在应用程序模块的函数中分配$compile$rootScope服务,然后通过创建新的( ) 并包装元素的附加从 angular 上下文之外使用它们通过使用.windowrunscope$rootScope.new()$rootScope.apply()

回答by Ty Danielson

You really want to avoid doing any jquery if you can, but I ran into a similar problem not too long ago, here was my questionand the correct answer that should be able to help you out. The short answer is using $compile.

如果可以,您真的想避免使用任何 jquery,但不久前我遇到了类似的问题,这是我的问题和正确答案,应该可以帮助您。简短的回答是使用 $compile。

回答by Hari Das

Try this

尝试这个

angular.element($("#appendToDiv")).append($compile("<my-angular-directive />")($scope));