AngularJs學習筆記(2)——ng-include

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.