发布于 2017-05-05 09:55:13 | 199 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的AngularJS教程,程序狗速度看过来!

AngularJS 前端JS框架

AngularJS诞生于Google是一款优秀的前端JS框架,已经被用于Google的多款产品当中。AngularJS有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入,等等。


这篇文章主要介绍了AngularJS使用ng-inlude指令加载页面失败的原因与解决方法,对比不同浏览器错误提示分析了加载失败的原因及通过http访问的解决方法,需要的朋友可以参考下

本文实例讲述了AngularJS使用ng-inlude指令加载页面失败的原因与解决方法。分享给大家供大家参考,具体如下:

AngularJS中提供的ng-include指令,很类似于JSP中的<jsp:include>用来将多个子页面合并到同一个父页面中,避免父页面过大,可读性差,不好维护。

父页面parent.html代码如下:


<html>
 <head>
  <script src="angular-1.2.2/angular.js"></script>
  <script>
   function rootController($scope,$rootScope,$injector)
   {
    $rootScope.name = "aty";
    $rootScope.age = 25;
   }
  </script>
 </head>
 <body ng-app ng-controller="rootController">
    <h1>Hello, {{name}}!</h1>
    <h1>Hello, {{age}}!</h1>
  <div id="included" ng-include="'child.html'">
      <input type="button" value="2"/>
    </div>
 </body>
</html>

被包含的子页面child.html代码如下:


<div>
    <h1>included, {{name}}!</h1>
    <h1>included, {{age}}!</h1>
</div>

我用IE11和Chrome39运行parent.html,发现child.html页面不能包含到parent.html中。IE下报错信息如下:

Error: 拒绝访问。
   at Anonymous function (file:///D:/learn/angular-1.2.2/angular.js:7852:7)
   at sendReq (file:///D:/learn/angular-1.2.2/angular.js:7720:9)
   at serverRequest (file:///D:/learn/angular-1.2.2/angular.js:7454:9)

chrome下报错信息如下:

XMLHttpRequest cannot load file:///D:/learn/include.html.
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/learn/include.html'.

IE下的提示有些晦涩,不过chrome提示很明显:不能跨域访问。通过上面的错误提示,可以看到:使用ng-include指令的时候,会用到AJAX请求XMLHttpRequest。但是我们是直接用浏览器打开的parent.html,并没有通过web容器访问,所以存在跨域访问问题,加载child.html也就失败了。解决办法很简单:将代码部署到tomcat等web容器下,通过http访问即可。

平时在练习JavaScript或者是JS框架的时候,一版都是使用比较轻量级的工具,不会使用像Eclipse之类IDE,我一般使用Notepad++编写js代码。Notepad++可以方便地调用本机安装的浏览器。像ng-include这样的指令,必须要有web容器的支持。可以使用前端开发神器webstorm,该工具运行html的时候,会自动启动内置的web容器,这样ng-include指令就不会报错了。

希望本文所述对大家AngularJS程序设计有所帮助。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务