8

我試圖通過角度服務編譯指令,但不幸的是它不起作用。 這個想法是在彈出窗口中顯示錯誤。在angularjs中通過服務編譯指令

我修改$ exceptionHandler的服務:

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

彈出服務看起來是這樣的:

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

不,我不能直接使用它。該錯誤如下所示:「未捕獲的錯誤:循環依賴:$ compile < - popup < - $ exceptionHandler < - $ rootScope」 – user2573863

+1

在Angular 1.2中不起作用,它要求將作用域作爲參數 – perrohunter

+3

來修復可以注入'$ rootScope'並執行'$ rootScope。$ new()'創建一個新的範圍,更新答案。 – Less