2013-02-19 19 views
18

Artık görevim $ exceptionHandler sağlayıcısını yeniden yazarak mesajla kalıcı iletişim kuracak ve varsayılan etkinliği durduracaktır.AngularJs/.provider/Bir yayın yapmak için rootScope nasıl alınır?

yapmam gerekenler:

.provider('$exceptionHandler', function(){ 

//and here I would like to have rootScope to make event broadcast 

}) 

standart enjekte yöntemi çalışmıyor: Proje init

Ben metod .provider kullanın.

UPD: kum havuzu - http://jsfiddle.net/STEVER/PYpdM/ Sen $ rootScope enjekte etmek gerek

cevap

31

Enjektör enjekte edebilir ve $ rootScope'u arayabilirsiniz.

Demo plunkr: http://plnkr.co/edit/0hpTkXx5WkvKN3Wn5EmY?p=preview

myApp.factory('$exceptionHandler',function($injector){ 
    return function(exception, cause){ 
     var rScope = $injector.get('$rootScope'); 
     if(rScope){ 
      rScope.$broadcast('exception',exception, cause); 
     } 
    }; 
}) 

Güncelleme: çok .provider eklemek tekniği: Bunu yapmanın

app.provider('$exceptionHandler', function() { 
    // In the provider function, you cannot inject any 
    // service or factory. This can only be done at the 
    // "$get" method. 

    this.$get = function($injector) { 
    return function(exception,cause){ 
     var rScope = $injector.get('$rootScope'); 
     rScope.$broadcast('exception',exception, cause); 
    } 
    }; 
}); 
+0

Bu durum sorunu çözdüyse de, bir sağlayıcı yapılandırmasına (örneğin .provider örneği: https://gist.github.com/Mithrandir0x/3639232) enjekte edilen "$ rootScope" öğesine ihtiyacınız varsa, bu yöntem çalışmayacaktır. – Webnet

+0

Tamam çalışıyor gibi görünüyor. İşte bir plunkr: http://plnkr.co/edit/svRUruKSzuLcBPAWa0ro?p=preview – checketts

+0

Sanırım şu anda yapamadık, ama şimdi bunu yapabilirsin. $ Get = function ($ rootScope) afaik – Ellone

-2

:

.provider('$exceptionHandler', '$rootScope', function(){ 

//and here I would like to have rootScope to make event broadcast 

}) 

bu denedin şey mi? Ve eğer öyleyse, neden başarısız olduğunu görmek için bir hata mesajınız veya bir jsfillde/plnkr var mı?

+0

Standart dediğim gibi yol çalışmıyor. –

+0

Evet, ancak işe yaramıyorsa ya yanlış kullanıyorsunuz ya da görünür bir etkiye sahip olmanıza ya da bir hata üretmeniz gerekiyor. Eğer jsfiddle yaparsanız, size yardım etmemiz çok daha kolay olacaktır. – martijnve

+0

jsfiddle zaten eklendi –

1

Benim yöntemim - Bir yönetmeni kullanarak ve bilinmeyen önceki durum işleyici geri dönerek hatalar:

app.config(function ($provide) { 
    $provide.decorator('$exceptionHandler', function($delegate, $injector) { 
    return function (exception, cause) { 
     if (ICanHandleThisError) { 
     var rootScope= $injector.get('$rootScope'); 
     // do something (can use rootScope) 
     } else 
     $delegate(exception, cause); 
    }; 
    }); 
});