如果你是一個angular的開發者的話,對於ng-html2js你應該 很熟悉。對於angular的指令,我們經常需要定義模板( directive template/templateUrl),你可以選擇講html page 放在真正的的web容器中寄宿,也可以選擇angular的ng-template 放在view的page之上,抑或也可以講html打成一個js文件和directive 的js文件合並在一起發布。
-
對於直接寄宿在web容器.
這很簡單,直接放在jetty,tomcat,iis, 抑或node express public目錄下。這里沒什么可以多說的,所以我們跳過。
-
angular ng-template模板:
代碼如下:
<script type="text/ng-template" id="/tpl.html"> Content of the template. </script>
這將會在angular的compile時候解析,angular將會把它放在angular的$templateCache 中。
對於$templateCache,如其名 這是angular對模板的緩存的service。在啟用了$templateCache的$http ajax請求, angular將會首先在$templateCache中查找是否有對此url的緩存:
$templateCache.get('templateId.html')
如果存在緩存,着angular將會直接用緩存中獲取,並不會在發送一次ajax。 對於所有的指令和模板angular默認啟用了templateCache。
這在於angular所處理的模式開發很有關系的。我們經常提到的SPA(single page application) 我們把view的顯示處理等表現邏輯推到了前段,而后端提供只與數據有關的soap/restful service 這樣對於一個應用程序業務邏輯來說不變的是處理數據的業務邏輯,這份邏輯你可以共享在不管前端是mobile app 或者是瀏覽器,或者winform gui的圖形化程序,因為對於同一個業務這是不變的。將view的分離推到各自的客戶端 將是更好的解決方案。
回到angular $templateCahce,對於一個應用程序view的分離,之后在對於當前的應用程序平台,html/js/css 這類資源是靜態的,最好是不變的,那么你可以自由的緩存在客戶端,減少服務器的交互,以及為了更大的性能追求,我們 可以把這類靜態資源放在Nginx這里反向代理或者CDN上,讓我們的程序獲取更大的性能和擴展空間。
-
回到angular的ng-html2js:
有了上邊對於$templateCache的理解,那你應該很容易理解html2js的方式了,與ng-template不同的 是ng-template是angular在compile的時候自動加入$templateCache的,html2js是我們在開發 時候利用build自己放入$templateCache。
angular.module('myApp', []) .run(function($templateCache) { $templateCache.put('templateId.html', 'This is the content of the template' ); });
形如上面的輸出,將html文件打成一個js文件。
這你也許在angular的單元測試karma unit test中看見過, karma-ng-html2js-preprocessor ,還有如果你也希望在build時候做到如此,那么你可以 使用grunt plugin grunt-html2js.
但使用grunt plugin的前提是你在你的項目中引入的grunt build的work flow,那么你可以在gruntfile.js中幾行代碼輕松的搞定。但是如果 你和我一樣 使用的是java的maven或者是gradle 作為build,那么你可以嘗試博主的maven plugin nghtml2js. 使用方式如下:
<plugin> <groupId>com.github.greengerong</groupId> <artifactId>nghtml2js</artifactId> <version>0.0.3</version> <configuration> <module>demo.template</module> <html>${project.basedir}</html> <extensions> <param>tpl</param> <param>html</param> </extensions> </configuration> <executions> <execution> <id>nghtml2js</id> <phase>generate-resources</phase> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin>