2

アプリ内でディレクティブを宣言できるようにすることで、AngularJS がカスタム タグ/要素を有効にする方法が本当に気に入っていますが、カスタム タグを動的に追加しても何も起こりません。

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

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

カスタム タグのインスタンスを動的に構築するにはどうすればよいですか?

4

1 に答える 1

2

angularの外でjqueryを呼び出すのはなぜですか? 通常、たとえば角度ディレクティブ内から何かを行い、$compile にアクセスできます。外部へのアクセスが絶対に必要な場合は、インジェクターを作成できます。 (プランカー)

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));
  });
});
于 2013-06-15T21:44:05.843 に答える