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

bla*_*ter 51 jquery angularjs

有没有办法用jQuery方法添加一个Angular指令的元素,append()并让Angular进行编译/链接,使其工作就好像你首先包含了该指令一样?

例:

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

$("body").append("<my-angular-directive />");
Run Code Online (Sandbox Code Playgroud)

它目前只是附加一个名为"my-angular-directive"的空DOM元素,但是Angular不会启动并发挥它的魔力.

art*_*iak 76

正确的方法是使用:$ compile并且如果你的指令返回:( directive definition object这是btw.推荐的方法)你可以调用link它上面的函数(scope例如注入).

$('body').append($compile("<my-angular-directive />")(scope));
scope.$apply(); 
Run Code Online (Sandbox Code Playgroud)

  • 你的代码不完整.请你发一个jsfiddle版本你的代码. (3认同)

Dav*_*ver 17

一个完整的例子,来自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);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)