看了下angular 的route,用它做个非常简单的单页面应用,记录一下。
顺便说下,好处是,页面改变时不需要刷新,而每个页面都展现不同的数据。尤其在使用模板页的时候,非常方便。
一 示例
- 项目结构:
index.html
script.js
------pages
---------home.html
---------about.html
---------cantact.html
- 项目代码
<1>.index.html
<!DOCTYPE html> <html ng-app="scotchApp"> <head> <title>Angular Routing Example</title> <link rel="stylesheet" href="libs/bootstrap/css/bootstrap.min.css" /> <link rel="stylesheet" href="libs/font-awesome-4.3.0/css/font-awesome.css" /> </head> <body ng-controller="mainController"> <header> <nav class="navbar navbar-default"> <div> <div> <a href="/">Angular Routing Example</a> </div> <ul class="nav navbar-nav navbar-right"> <li><a href="#home"><i class="fa fa-home"></i> Home</a></li> <li><a href="#about"><i class="fa fa-shield"></i> About</a></li> <li><a href="#contact"><i class="fa fa-comment"></i> Contact</a></li> </ul> </div> </nav> </header> <div id="main"> <div ng-view></div> </div> <script src="libs/angular1.3.15/angular.min.js"></script> <script src="libs/jquery2.1.3/jquery.min.js"></script> <script src="libs/angular1.3.15/angular-route.min.js"></script> <script src="script.js"></script> </body> </html>
<2>.script.js
var appModule = angular.module(‘scotchApp‘, [‘ngRoute‘]); // configure our routes appModule.config(function($routeProvider) { $routeProvider // route for the home page .when(‘/home‘, { templateUrl : ‘pages/home.html‘, controller : ‘mainController‘ }) // route for the about page .when(‘/about‘, { templateUrl : ‘pages/about.html‘, controller : ‘aboutController‘ }) // route for the contact page .when(‘/contact‘, { templateUrl : ‘pages/contact.html‘, controller : ‘contactController‘ }) .otherwise(‘/home‘); }); var mainCtrl = function($scope){ $scope.message = ‘Everyone come and see how good I look!‘; } var aboutCtrl = function($scope){ $scope.message = ‘Look! I am an about page.‘; } var contactCtrl = function($scope){ $scope.message = ‘Contact us! JK. This is just a demo.‘; } appModule.controller(‘mainController‘, mainCtrl); appModule.controller(‘aboutController‘, aboutCtrl); appModule.controller(‘contactController‘, contactCtrl);
<3>.运行效果:
二 遇到的问题:
- 出现错误:Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
解决:因为我是以文件的形式打开的,由于chrome 的设置问题,只支持http, data, chrome, chrome-extension, https, chrome-extension-resource 这些格式,不支持file:///xxxx.html 这种格式,所以会出现这个问题。
方法一:启动chrom 参数
-
--allow-file-access-from-files
方法二:启动tomcat,把你的文件全扔到webapps 里,然后在浏览器里访问,就可以了。
时间: 2024-10-31 00:56:02