8

私はアンギュラサービスを介してディレクティブをコンパイルしようとしていますが、残念ながらそれは動作しません。 アイデアは、ポップアップでエラーを表示することです。angularjsのサービスを介してディレクティブをコンパイル

crm.factory('$exceptionHandler', function(popup) { 
    return function(exception) { 
     popup.open({message: exception}); 
    } 
}); 

サービスはこのようになりますポップアップ:

私は$ exceptionHandlerのサービス変更した

crm.factory('popup', function ($document) { 
    return { 
     open: function (data) { 
      var injector = angular.element(document).injector(), 
       $compile = injector.get('$compile'), 
       template = angular.element('<popup></popup>'); 

      // var ctmp = $compile(template.contents()); 
      $compile(template.contents()); 

      $document.find('body').append(template); 
     } 
    }; 
}); 

をそして私は、これはに良いアイデアだったとは思いませんハードコード$コンパイルサービス(しかし、私は角度でこれを実現する方法はありません):

$compile = injector.get('$compile') 

ポップアップディレクティブ

crm.directive('popup', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     templateUrl: '/public/js/templates/common/popup.html', 
     link: function() { 
      console.log('link()'); 
     }, 
     controller: function() { 
      console.log('ctrl()'); 
     } 
    }; 
}); 

これを行うには、他のいくつかの方法があることができますか?おかげさまで

答えて

1

また、あなたはかなり正確$compileを使用していない、あなたのサービスに直接$compileを注入することができます

//commented alternative lines for allowing injection and minification since reflection on the minified code won't work 
//crm.factory('popup', ['$document', '$compile', function ($document, $compile) { 
crm.factory('popup', function ($document, $compile) { 
    return { 
     open: function (data) { 
      var template = angular.element('<popup></popup>'), 
       compiled = $compile(template); 

      $document.find('body').append(compiled); 
     } 
    }; 
}); 
//closing bracket for alternative definition that allows minification 
//}]); 
+2

いや、私はそれを直接使用することはできません。エラーは次のようになります: "Uncaught Error:循環依存性:$ compile < - popup < - $ exceptionHandler < - $ rootScope" – user2573863

+1

Angular 1.2では機能しません、パラメータとしてスコープを問い合わせます – perrohunter

+3

'$ rootScope'と' $ rootScope。$ new() 'を実行して新しいスコープを作成し、答えを更新しました。 – Less

関連する問題