简体   繁体   English

Angular.js模板未加载

[英]Angular.js templates not loading

I am new to angular.js and just trying to get my head around the basics and hopefully this is something simple, but I am having trouble loading in a templateUrl. 我是angular.js的新手,只是想着手掌握基础知识,希望这很简单,但是在将templateUrl加载时遇到了麻烦。

My index.html is as follows: 我的index.html如下:

<!DOCTYPE html>
<html ng-app="app">
<head>
  <title>AngularJS Tutorials</title>
</head>
<body>
  <div ng-app="app">
    <h1>Introduction to Angular.JS</h1>
    <div ui-view></div>
  </div>



  <!-- Scripts -->
  <script type="text/javascript" src="js/angular.min.js"></script>
  <script src="js/angular-ui-router.min.js"></script> 
  <script type="text/javascript" src="js/app.js"></script>
</body>
</html>

My app.js is: 我的app.js是:

angular
    .module('app', [
        'ui.router'
    ])
    .config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
        $urlRouterProvider.otherwise('/');

        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: 'templates/home.html'
            })
    }])

My home.html is: <h1>home template</h1> 我的home.html是: <h1>home template</h1>

So I dont know why this isn't working, but the error is: 所以我不知道为什么这不起作用,但是错误是:

XMLHttpRequest cannot load file:///Users/code/Desktop/angular/templates/home.html. Cross origin requests are only supported for HTTP. 

Thanks in advance, Gab 在此先感谢,Gab

This error comes due to a security restriction put by the browser. 此错误是由于浏览器施加的安全限制而引起的。 You can try below steps: 您可以尝试以下步骤:

  • Try to run your code in some other browsers 尝试在其他浏览器中运行代码
  • Add the templates inside index.html itself by placing the content inside script tag. 通过将内容放在script标记内,将模板添加到index.html本身内。 These script elememts should appear after ng-app . 这些脚本elememts应该出现在ng-app ( ref link ) 参考链接

    <script type="text/ng-template" id="home.html"> Content of the template goes here </script>

First thing you use <ng-view> </ng-view> for loading your templates. 首先,您使用<ng-view> </ng-view>加载模板。 and second is use <script type="text/ng-template" id="home.html"> for you each partial view. 第二个是对每个局部视图使用<script type="text/ng-template" id="home.html"> third thing is not mandatory but use otherwise at last that makes sense. 第三件事不是强制性的,但最后还是可以使用。 Here is fiddle for you check it out fiddle 这是小提琴,您可以检查一下小提琴

If you want to run your page locally, I suggest you install a http-server and run it in there ... Then you avoid CORS issues like that 如果要在本地运行页面,建议您安装一个http服务器并在其中运行...然后避免出现类似的CORS问题

Example: with node.js installed 示例:安装了node.js

cd ~/myProjectFolder

npm i http-server

http-server ./

Then you could also just enter localhost:8080 in your browser and wouldn't have to point it to some URI/folder 然后,您也可以在浏览器中输入localhost:8080 ,而不必将其指向某个URI /文件夹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM