在项目开发过程中,我们都用ui路由来开发项目,因为ui路由有三个重要的特性:多视图、嵌套视图、视图命名。
具体ui-router的使用及功能请参考:http://ui-router.github.io
首先看一下,项目中某个模块的目录结构:
看到每个模块下都会有自己的路由配置文件,下面我们看怎么从启动app开始,配置动态加载路由的功能:
var app=angular.module("myApp",["ui.router","main"]); app.config(["$stateProvider","$urlRouterProvider","$sceDelegateProvider", function($stateProvider,$urlRouterProvider,$sceDelegateProvider) { /*设置白名单(跨域访问名单)*/ $sceDelegateProvider.resourceUrlWhitelist([ "self", "http://datainfo.duapp.com/**" ]) /*默认访问首页*/ $urlRouterProvider.otherwise("/main"); $stateProvider .state({/*首页*/ name:"main", url:"/main", template:"<main-com></main-com>" }).state({ name:"main.classify", //main页面的下classify(用于展示商品分类的) url:"/classify", template:"<list-com></list-com>", params:{classID:null} }) }])使用ui路由时需要在模块中,注入ui.router到AngularJS主模块中。然后将main模板也注入到主模板中。
template:"<main-com></main-com>" 是要打开的模板组件名字我们就详细的看下主页面main的详细代码:
JS代码:
var main = angular.module("main", []); main.component("mainCom",{ templateUrl:"component/main/main.html", controller:["$scope","$http", function($scope,$http){ $scope.classify=[]; //定义一个空数据,可以省略 $http({ method:"GET", url:"请求的地址" }).then( function success(resp){ console.log(resp) $scope.classify=resp.data; },function error(resp){ console.log("请求失败") } ) }] })HTML代码:
<ul> <li ng-repeat="c in classify"> <a ui-sref=".classify({classID:c.classID})"> <span ng-bind="c.className"></span> </a> </li> </ul> <div ui-view></div>ui-sref:用于代替按标签的href属性
goodeslist页面(用于获取商品列表)我的详细代码:
JS代码:
var goodeslist=angular.module("goodeslist",[]); goodeslist.component("listCom",{ templateUrl:"example/goodes/goodeslist.html", controller:["$scope","$http","$stateParams", function($scope,$http,$stateParams){ //$stateParams用来传递参数 $scope.goodes=[];//定义一个空数据,可以省略 $http({ method:"JSONP", url:"请求的商品列表路径", //$stateParams.classID 将calssID作为参数传递过来 classID:$stateParams.classID } }).then( function success(resp){ console.log("请求成功", resp); $scope.goodes=resp.data; },function error(resp){ alert("系统繁忙请稍后再试") } ) }] })这里获取到的为jsonp对象,需要通过跨域也就是通过设置白名单的方式来访问。
$stateParams 是ui路由中用来传递参数的HTML代码:
<div ng-repeat="g in goodes"> <div> <img ng-src={{g.goodsListImg}}> //输出图片 <div> <p ng-bind="g.goodsName></p> //输出商品名字 <p ng-bind="g.price></p> //输出价格 <p> <a href="#">立即购买</a> <a href="#">加入购物车</a> </p> </div> </div> </div>这样就可以在页面展示商品信息了。