为什么要添加动态元素时,是angular.js不够聪明编译DOM? [英] Why is angular.js not smart enough to compile DOM when adding dynamic elements?

查看:188
本文介绍了为什么要添加动态元素时,是angular.js不够聪明编译DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢AngularJS如何支持自定义标签/元素允许你声明你的应用程序内的指令,但是,当我追加动态自定义的标签,没有任何反应:

I really like how AngularJS enables custom tags/elements by allowing you to declare directives inside your app, however, when I append a custom tag dynamically, nothing happens:

angular.module('myApp', []).directive('test', (($compile) ->
   restrict: 'E'
   link: (scope, element, attributes) ->
     $(element).html('<h1>this is a test!</h1>')
))

$('body').append('<test></test>')

我如何动态地建立我的自定义标签的一个实例?

How can I build an instance of my custom tag dynamically?

推荐答案

为什么你叫角以外的jQuery?通常你会从实例的角度指令里面做一些事情,并且将有机会获得$编译。如果你绝对需要访问外,您可以创建一个注射器。 (PLUNKER)

Why are you calling jquery outside of angular? Normally you would do something from inside an angular directive for instance and that would have access to $compile. If you absolutely need access outside you can create an injector. (PLUNKER)

angular.module('myApp', []).directive('test', function($compile) {
  return {
    restrict: 'E',
    link: function(scope, element, attributes) {
      $(element).html('<h1>this is a test!</h1>')
    }
  }
});

///////////////////////////////////////////////////////////////////////////////
// called outside angular, you can create an injector that knows about
// certain modules
///////////////////////////////////////////////////////////////////////////////
$(function() {
  // myApp for test directive to work, ng for $compile
  var $injector = angular.injector(['ng', 'myApp']);
  $injector.invoke(function($rootScope, $compile) {
    $('body').prepend($compile('<test>Inside injector</test>')($rootScope));
  });
});

这篇关于为什么要添加动态元素时,是angular.js不够聪明编译DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆