2016-11-18 68 views
0

Synchronously registering a decoratorAngular:爲什麼延遲加載裝飾器不起作用?

angular 
    .module('myApp') 
    .decorator('$controller', MyDecorator); 

angular 
    .module('myApp') 
    .controller('MyCtrl', MyCtrl); 

Asynchronously registering a decorator

$timeout(function() { 
    angular 
    .module('myApp') 
    .register 
    .decorator('$controller', MyDecorator); 

    // Make sure controller is registered after decorator 
    $timeout(function() { 
    angular 
     .module('myApp') 
     .register 
     .controller('MyCtrl', MyCtrl); 
    }, 1000); 
}, 1000); 

爲什麼沒有第二個例子中工作?

+0

什麼不行?什麼是錯誤信息? 「MyDecorator」做了什麼,它在哪裏使用? – Bergi

+0

Angular不支持延遲加載的組件。你可以看看[ocLazyLoad](https://github.com/ocombe/ocLazyLoad)。 – zeroflagL

+0

@Bergi沒有錯誤,它只是不運行 –

回答

1

如你所知,AngularJS具有引導過程中2個不同的階段:

  1. 配置階段
  2. 運行階段

official documentation

模塊是一個集合配置運行塊,在引導過程中將 應用於應用程序。在其最簡單的 形成模塊有二種的 塊的集合:

  1. 配置塊 - 在供應商登記和配置階段得到執行。只有提供者和常量 可以注入到配置塊中。這是爲了防止 在完全配置完成 之前意外實例化服務。
  2. 運行模塊 - 在創建注入器後執行並用於啓動應用程序。只有實例和常量可以注入到運行塊中 。 這是爲了防止在應用程序運行時間期間進一步的系統配置 。

在報價上面我已經強調了一句約運行塊

這是應用程序運行 時間內,以防止進一步的系統配置現在

,在AngularJS documentation about decorator

$provide.decorator一樣,module.decorator函數在應用程序的配置階段運行 。這意味着您可以在定義裝飾服務之前定義一個 module.decorator。

因此,一個控制器(或服務或過濾器)的裝飾在配置階段不在運行階段完成。

因此,您的「異步註冊裝飾器」示例不起作用:您正試圖定義和修飾initCtrl函數中的控制器。但後者在運行階段中被調用,並且在此階段定義新的裝飾器爲時已晚。

+0

我使用的是1.5角,但是答案似乎是有效的,無論版本。你知道如何(如果可能)我能達到這樣的效果嗎? –