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 <- $ exceptionHandler <- $ rootScope" – user2573863

+1

Angular 1.2에서는 작동하지 않습니다. 범위를 매개 변수로 요청합니다. – perrohunter

+3

'$ rootScope' 그리고'$ rootScope. $ new()'를 사용하여 새로운 범위를 만들고 답변을 업데이트하십시오. – Less

관련 문제