0

我在我的Angular應用程序中使用RequireJS。我想require我的pill它實際使用。需要指令模板

pill.js

define([], function() { 
    angular.module('app').directive('pill', function() { 
     return function(a,b,c) { 
      b.html("A pill"); 
     }; 
    }); 
}); 

incl.html

<div load-script="require(['pill']);"></div> 
<div pill>test</div> 

main.html中

<html ng-app="app"> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script> 
     <script src="http://requirejs.org/docs/release/2.1.10/comments/require.js"></script> 
    </head> 
    <body> 
     <script> 
      var app = angular.module("app", []) 
       app.directive('loadScript', function() { 
         return { 
          link: function(scope, element, attrs) { 
           (new Function(attrs.loadScript))(); 
          } 
         }; 
        } 
       ); 
     </script> 
    <div ng-include="'incl.html'"></div> 
    </body> 
</html> 

此簡短的例子應該DECL是一個pill指令,它只是將test中的文本轉換爲incl.html文件中的A pill。但是,它不起作用。我猜這是因爲pill指令是在編譯incl.html後註冊的。

我想避免宣佈指令somwhere例如在main.html內,因爲它沒有在那裏使用。這個要求是否可以用優雅的方式實現?

回答

0

根據需要加載directive的最佳方式是使用$compileProvider創建它,在您的app.config階段需要緩存。此外,我不建議您使用ng-include,而是在加載使用它的局部視圖時加載所需的directive

要做到這一點,它實際上很複雜。我創建了以下庫,應該可以幫助你開始:

http://marcoslin.github.io/angularAMD/

angularAMD將使它更容易爲你創建一個獨立的文件,讓您只在需要它的諧音配置RequireJS依賴加載directive