標籤:code 技術分享 htm storm 錯誤 瀏覽器 src images rip
編寫html文檔的時候,為了實現代碼模組化,增加複雜頁面的代碼可讀性和可維護性,我們常常會想到將代碼分散寫入不同的HTML檔案
angularJS裡面的ng-include指令結合ng-controller能夠很方便的實現這個目的
ng-include 指令用於包含外部的 HTML 檔案。
ng-include可以作為一個屬性,或者一個元素使用
demo樣本如下:
index.html
<!doctype html><html ng-app="myApp"><head> <meta charset="UTF-8"> <title>demo</title> <!-- angularjs引用 --> <script type="text/javascript" src="angular/angular.min.js" charset="utf-8"></script> <script type="text/javascript" src="subPage.controller.js" ></script></head><body ng-controller="myCtrl"> <div ng-include="‘subPage.html‘"></div> <!-- 路徑裡面必須帶上單引號 --></body></html>
subPage.html
<div id="subPage"> <label>{{title}}<label> <input ng-model="value"> <img src="eg_tulip.jpg" alt="上海鮮花港 - 鬱金香" style="width:400px;height:200px" /></div>
subPage.controller.js
var app = angular.module(‘myApp‘,[]);app.controller("myCtrl",function($scope){ $scope.title="類型"; $scope.value="圖片";});
直接在google瀏覽器上運行index.HTML,報錯
XMLHttpRequest cannot load file:///D:/learn/include.html.
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https
提示很明顯:不能跨域訪問。通過上面的錯誤提示,可以看到:使用ng-include指令的時候,會用到AJAX請求XMLHttpRequest
像ng-include這樣的指令,必須要有web容器的支援。直接用瀏覽器開啟的index.html,並沒有通過web容器訪問,所以存在跨域訪問問題
解決方案:
1.將代碼部署到tomcat或者iis等web容器下,通過http訪問即可
2.可以使用前端開發神器webstorm,該工具運行html的時候,會自動啟動內建的web容器
AngularJs學習筆記(2)——ng-include