本文實例分析了AngularJS使用ng-app自動加載bootstrap框架問題。分享給大家供大家參考,具體如下:
前面的文章《AngularJS框架的ng-app指令與自動加載實現方法分析》 提出了使用ng-app指令的情況。之前覺得出現第4和第5種情況很奇怪,因為只看到了現象,沒有看到本質。JS錯誤,最直觀的表現方式就是:彈出一個非常不友好的JS錯誤窗口。當腳本出現了未捕獲的錯誤,瀏覽器才會彈出錯誤提示。還有一種比較隱晦的表示:在瀏覽器的控制臺輸出錯誤信息。這提示我們:使用JS框架的時候,一定要用下F12看看控制臺是否有錯誤。
第3種情況 和 第5種情況:不帶屬性的ng-app模塊不能自動加載,用F12發現控制臺報錯:
SCRIPT5022: [$injector:modulerr] Failed to instantiate module app1 due to:
Error: [$injector:nomod] Module 'app1' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument。
什么意思呢?大概就是我們使用了ng-app,要求自動加載我們自定義的模塊,但是我們卻沒有提供這些模塊。再看下官方的ngApp說明文檔:
Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the <body> or <html> tags.Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application。
1、如果在html中定義了ng-app,那么angular框架會自動初始化,不管它有沒有帶屬性值;
如果沒有使用ng-app,那么需要自己手動初始化。
2、如果ng-app沒有屬性值,angular會默認創建一個模塊作為root,然后啟動框架。
3、ng-app屬性如果有值,即自定義module,也會被解析出來,前提是我們必須先創建module。
也就是說ng-app就是用來自動啟動angular框架的,是否帶屬性值的差別在于:根模塊的創建,到底是默認的,還是我們自定義的。
更多關于AngularJS相關內容感興趣的讀者可查看本站專題:《AngularJS入門與進階教程》及《AngularJS MVC架構總結》
希望本文所述對大家AngularJS程序設計有所幫助。
新聞熱點
疑難解答