Angular路由与多视图综合案例

    Ajax请求存在的几个问题

(1)Ajax请求不会留下History 记录,会导致浏览器后退按钮失效

(2)用户无法直接通过URL进入应用中的指定页面(保存书签、链接分享给朋友)

(3)Ajax对SEO(Search Engine Optimization)是一个灾难

    解决方案

 (1)使用hash,监听hashchange事件来进行视图切换;(接下来将会说明的routeProvider路由机制

 (2)HTML5的history API通过pushState()记录操作历史,监听popstate事件来进行视图切换,也有人把这叫pjax技术

如此一来,便形成了通过地址栏进行导航的深度链接(deeplinking ),也就是我们所需要的路由机制。通过路由机制,一个单页应用的各个视图就可以很好的组织起来了。

以上均参考整理来自走进AngularJs(八) ng的路由机制

    定义路由$routeProvider表参数说明

//module
var app = angular.module('myApp', ['ngRoute', 'myAppController','myAppServer', 'myAppFilter']);

//==============================================================================================
//$routeProvider提供了定义路由表的服务,它有两个核心方法,
// when(path,route)和otherwise(params)
// path是一个string类型,表示该条路由规则所匹配的路径,它将与地址栏的内容($location.path)值进行匹配
// route 参数是一个object,用来指定当path匹配后所需的一系列配置项,包括以下内容
// controller //function或string类型。在当前模板上执行的controller函数,生成新的scope
// controllerAs //string类型,为controller指定别名
// template //string或function类型,视图所用的模板,这部分内容将被ngView引用
// templateUrl 
// resolve //指定当前controller所依赖的其他模块
// redirectTo //重定向的地址
app.config(function($routeProvider){
	$routeProvider.when('/main', {
        //string或function类型,当视图模板为单独的html文件或是使用了<script type="text/ng-template">定义模板时使用
		templateUrl:'templ/list.html',
        //function或string类型。在当前模板上执行的controller函数,生成新的scope
		controller : 'listController'
	}).when('/edit/:id', { 
		templateUrl:'templ/edit.html',
		controller : 'editController'
	}).when('/view/:id', {
		templateUrl:'templ/view.html',
		controller : 'viewController'
	}).when('/about', {
		templateUrl:'templ/about.html',
		controller : ''
	}).when('/routeDetail', {
		templateUrl:'templ/routeDetail.html',
		controller: ''
	}).otherwise({
		//重定向的地址
		redirectTo: '/main' 
	});
});

    $routeProvider路由与多视图综合案例

上述案例源代码下载请点击 

遇到Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. 

解决方案请狠狠点击这里

原文地址:https://www.cnblogs.com/zjf-1992/p/6534295.html