<div ng-view></div> //或者 <ng-view></ng-view>
该 div 内的 HTML 内容会根据路由的变化而变化。
5. 在config配置阶段,注入$routeProvider,进行路由配置:
.config(function($routeProvider){ $routeProvider .when("http://www.cnblogs.com/",{template:'<h1>这是首页</h1>'}) .when("/page1",{templateUrl:"page.html",controller:"ctrl1"}) .when("/page2",{templateUrl:"page.html",controller:function($scope){ $scope.text = "这是ctrl不知道是几控制器!!" }}) .when("/page3",{templateUrl:"page.html"}) .when("/page4",{}) .otherwise({redirectTo:"http://www.cnblogs.com/"}) })
二、AngularJS 路由也可以通过不同的模板来实现。
$routeProvider.when 函数的第一个参数是 URL 或者 URL 正则规则,第二个参数为路由配置对象。
路由配置对象语法规则如下:
1 $routeProvider.when(url,{ 2 template:string, //在ng-view中插入简单的html内容 3 templateUrl:string, //在ng-view中插入html模版文件 4 controller:string,function / array, //在当前模版上执行的controller函数 5 controllerAs:string, //为controller指定别名 6 redirectTo:string,function, //重定向的地址 //指定当前controller所依赖的其他模块 8 });
三、路由对象中接受的可选参数:
① template: 自定义HTML模板,会直接将这段HTML记载到ng-view中;
.when("/page3",{templateUrl:"page.html"})
② templateUrl: 导入外部的HTML模板文件。 为了避免冲突,外部的HTML应该是一个代码片段,即只保留body以内的部分。
.when("/page1",{templateUrl:"page.html",controller:"ctrl1"})
③ controller: 在当前HTML模板上,执行的controller函数。会生出新的作用域$scope. 可以接受字符串(声明好的controller名字),也可以直接接受函数。
.when("/page1",{templateUrl:"page.html",controller:"ctrl1"})
注意: 使用ng-view打开的页面,controller中的作用域是属于当前页面作用域的子作用域!! 依然符合Angular中父子作用域"能读不能写"的要求!
所以: 如果需要在ng-view中修改当前作用域的变量,必须把这个变量声明为对象的属性!!
④ redirectTo:重定向。一般用于.otherwise()中,用于重定向回首页!
.otherwise({redirectTo:"http://www.cnblogs.com/"})
最后举个栗子:
ul{ overflow li{ width height text-align float line-height list-style cursor li a{ text-decoration color li:hover{ background-color #div1{ width height margin border首页page1page2page3page4 angular.module(]) .config(function($routeProvider){ $routeProvider .when(}) .when(}) .when(($scope){ $scope.text }}) .when(}) .when(,{}) .otherwise({redirectTo:}) }) .controller(($scope){ $scope.test ; $scope.obj = { test: } }) .controller(($scope){ $scope.text ; })
结果:
作者编
到此,AngularJS的基础知识基本已经结束了。要知道,在很多公司中,AngularJS的应用要比jQuery要重要的多。不过小编对AngularJS的学习也并没有结束。以后小编也会将更多的AngularJS以及其他的前端知识带给大家!!