{"action":"created","issue":{"url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/issues/5","repository_url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection","labels_url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/issues/5/labels{/name}","comments_url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/issues/5/comments","events_url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/issues/5/events","html_url":"https://github.com/ShuyunXIANFESchool/FE-problem-collection/issues/5","id":161343209,"number":5,"title":"关于angular-ui-router使用","user":{"login":"silence717","id":8267830,"avatar_url":"https://avatars.githubusercontent.com/u/8267830?v=3","gravatar_id":"","url":"https://api.github.com/users/silence717","html_url":"https://github.com/silence717","followers_url":"https://api.github.com/users/silence717/followers","following_url":"https://api.github.com/users/silence717/following{/other_user}","gists_url":"https://api.github.com/users/silence717/gists{/gist_id}","starred_url":"https://api.github.com/users/silence717/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/silence717/subscriptions","organizations_url":"https://api.github.com/users/silence717/orgs","repos_url":"https://api.github.com/users/silence717/repos","events_url":"https://api.github.com/users/silence717/events{/privacy}","received_events_url":"https://api.github.com/users/silence717/received_events","type":"User","site_admin":false},"labels":[{"url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/labels/AngularJS","name":"AngularJS","color":"fef2c0"},{"url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/labels/%E5%88%86%E4%BA%AB","name":"分享","color":"d93f0b"}],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":1,"created_at":"2016-06-21T03:40:18Z","updated_at":"2016-07-17T09:03:45Z","closed_at":null,"body":"## angular-ui-router使用\r\n### github源码地址：[https://github.com/angular-ui/ui-router](https://github.com/angular-ui/ui-router)\r\n### api地址 [http://angular-ui.github.io/ui-router/site](http://angular-ui.github.io/ui-router/site)\r\n### 安装\r\n```javascript\r\nnpm install --save angular-ui-router\r\n```\r\n### 使用angular-ui-router\r\n备注： 以下所有示例代码来源于个人所写的练习.\r\n\r\n地址为：[https://github.com/silence717/angular-webpack-demo](https://github.com/silence717/angular-webpack-demo)\r\n##### 导入angular-ui-router\r\n```javascript\r\nimport uiRouter from 'angular-ui-router';\r\n```\r\n##### 在angular.module中注入angular-ui-router\r\n```javascript\r\n    angular.module('app',[uiRouter]);\r\n```\r\n##### 为了方便使用，将$state与$stateParams全部挂载到$rootScope，在angular.module中初始化\r\n```javascript\r\nfunction runBlock($rootScope, $state, $stateParams) {\r\n\t'ngInject';\r\n\r\n\t$rootScope.$state = $state;\r\n\t$rootScope.$stateParams = $stateParams;\r\n}\r\n```\r\n\r\n##### 定义路由规则，在angular.module中配置路由规则\r\n```javascript\r\nexport function routerConfig($urlRouterProvider) {\r\n\t'ngInject';\r\n\r\n\t// 默认路由设置\r\n\t$urlRouterProvider.otherwise('/home');\r\n\r\n\t// 无视浏览器中 url末尾的\"/\"\r\n\t// 设置时 url, 末尾不要添加 \"/\"\r\n\t$urlRouterProvider.rule(($injector, $location) => {\r\n    \tconst path = $location.path();\r\n    \tconst hashTrailingSlash = path[path.length -1] === '/';\r\n\r\n    \tif (hashTrailingSlash) {\r\n        \treturn path.slice(0, path.length -1);\r\n    \t}\r\n\t});\r\n}\r\n```\r\n##### 基于以上两部分的操作，完整的app初始化代码为\r\n```javascript\r\nangular\r\n\t.module('app', [uiRouter])\r\n\t.config(routerConfig)\r\n\t.run(runBlock);\r\n```\r\n##### 业务模块路由定义配置,我们通常建议将路由分散到自己的模块管理，所以只以单个作为示例\r\n```javascript\r\nexport const HomeRouter = {\r\n    state: 'home',\r\n    config: {\r\n        url: '/home',\r\n        views: {\r\n            '@': {\r\n                template: homeTpl,\r\n                controller: 'HomeController',\r\n                controllerAs: 'vm'\r\n            }\r\n        },\r\n        title: '好玩的app'\r\n    }\r\n};\r\n```\r\n##### 业务入口主文件导入，并且在angular.module中配置\r\n```javascript\r\nimport {HomeRouter} from './Routers';\r\n\r\nfunction config($stateProvider) {\r\n    'ngInject';\r\n    $stateProvider.state(HomeRouter.state, HomeRouter.config);\r\n}\r\n\r\nexport default angular\r\n    .module('app.home', [])\r\n    .config(config)\r\n    .name;\r\n```\r\n##### 页面的html如何书写\r\n```html\r\n<ul class=\"nav navbar-nav\">\r\n    <li ui-sref-active=\"active\"><a ui-sref=\"home\">首页</a></li>\r\n    <li ui-sref-active=\"active\"><a ui-sref=\"album\">相册</a></li>\r\n    <li ui-sref-active=\"active\"><a ui-sref=\"user.baseInfo\">个人中心</a></li>\r\n</ul>\r\n<div ui-view=\"\"></div>\r\n```\r\n\r\n### 在这里做一个简单常用的API的解释\r\n#### directive\r\n##### ui-sref：A directive that binds a link (<a> tag) to a state.\r\n##### ui-sref-active: A directive working alongside ui-sref to add classes to an element when the related ui-sref directive's state is active, and removing them when it is inactive.\r\n##### ui-view: The ui-view directive tells $state where to place your templates.\r\n\r\nui-view使用有三种，分别为：\r\n\r\n1. as element:\r\n```html\r\n<ui-view></ui-view>\r\n```\r\n2. as attribute:\r\n```html\r\n<ANY ui-view ></ANY>\r\n```\r\n3. as class:\r\n```html\r\n<ANY class=\"ui-view\"></ANY>\r\n```\r\n具体里面的参数不做介绍，自己查阅官方文档\r\n\r\n上面的html代码会被compile为：\r\n```html\r\n<ul class=\"nav navbar-nav\">\r\n    <li ui-sref-active=\"active\" ui-sref-active-eq=\"\" class=\"active\"><a ui-sref=\"home\" href=\"#/home\">首页</a></li>\r\n    <li ui-sref-active=\"active\" class=\"\"><a ui-sref=\"album\" href=\"#/album\">相册</a></li>\r\n    <li ui-sref-active=\"active\" class=\"\"><a ui-sref=\"user.baseInfo\" href=\"#/user/baseInfo\">个人中心</a></li>\r\n</ul>\r\n```\r\n### $state使用\r\n#### Methods\r\n##### get 获取当前state的配置信息\r\n```html\r\n    <a href=\"javascript:;\" ng-click=\"vm.getConfig();\">获取state配置</a>\r\n```\r\n```javascript\r\n    let config = this.state.get('user');\r\n    console.log(config);\r\n    // => Object {url: \"/user\", views: Object, title: \"个人中心\", name: \"user\"}...\r\n```\r\n##### go 跳转到一个新的state\r\n```html\r\n    <a href=\"javascript:;\" ng-click=\"vm.goUserCenter();\">这是一个跳转链接...</a>\r\n```\r\n```javascript\r\n    // 不带参数跳转\r\n    this.state.go('user.baseInfo');\r\n    // 带参数跳转\r\n    this.state.go('album.detail', {id: 1});\r\n```\r\n##### href 获取到当前state的href值\r\n```javascript\r\n    console.log(this.state.href('album.detail', {id: 0}));\r\n    // => #/album/0\r\n```\r\n##### includes 获取当前state是否包含某些state\r\n```javascript\r\n    console.log(this.state.includes('album'));\r\n    // => false\r\n```\r\n##### is Similar to $state.includes, but only checks for the full state name\r\n```javascript\r\n    console.log(this.state.is('home'));   //=> true\r\n```\r\n#### events\r\n##### $stateChangeStart  路由发生改变\r\n```javascript\r\nfunction stateChangeStart($rootScope) {\r\n    $rootScope.$on('$stateChangeStart',\r\n        (event, toState, toParams, fromState, fromParams) => {\r\n            // event.preventDefault();\r\n            console.log('开始改变=====');\r\n            console.log(toState);\r\n            console.log(toParams);\r\n            console.log(fromState);\r\n            console.log(fromParams);\r\n            // 开始改变=====\r\n            // app.js:48Object {url: \"/home\", views: Object, title: \"好玩的app\", name: \"home\"}\r\n            // app.js:49Object {}\r\n            // app.js:50Object {name: \"\", url: \"^\", views: null, abstract: true}\r\n            // app.js:51Object {}\r\n            // client.js:55 [HMR] connected\r\n        });\r\n}\r\n```\r\n##### $stateChangeError 路由转变出错，参数基本与$stateChangeStart一致，多一个error参数\r\n##### $stateChangeSuccess  路由转向成功，参数与$stateChangeStart完全一致\r\n##### $stateNotFound  未找到路由,demo copy于参照官网\r\n```javascript\r\n// somewhere, assume lazy.state has not been defined\r\n$state.go(\"lazy.state\", {a:1, b:2}, {inherit:false});\r\n\r\n// somewhere else\r\n$scope.$on('$stateNotFound',\r\nfunction(event, unfoundState, fromState, fromParams) {\r\n    console.log(unfoundState.to); // \"lazy.state\"\r\n    console.log(unfoundState.toParams); // {a:1, b:2}\r\n    console.log(unfoundState.options); // {inherit:false} + default options\r\n})\r\n```\r\n##### onEnter 可以配置进入路由to do something\r\n```javascript\r\nonEnter: function() {\r\n    console.log('enter user.footprint state');\r\n}\r\n```\r\n##### onExit 退出路由做什么\r\n```javascript\r\nonExit: function() {\r\n    // 用于初始化一些数据什么的,清空表单...\r\n    console.log('exit user.footprint state');\r\n}\r\n```\r\n### 部分知识点单列：\r\n#### 一、问: 多个页面可能使用相同的html模板,我们是要同样的代码写N遍吗? 答案肯定不是.那么问题来了,一个页面有多个模板文件,肿么办?\r\n1. 在html中给ui-view添加名字\r\n```html\r\n<div ui-view=\"content\"></div>\r\n<div ng-show=\"vm.isShowThumb\" class=\"module-content\"  ui-view=\"thumbList\"></div>\r\n<div ng-show=\"vm.isShowDetail\" ui-view=\"detailList\"></div>\r\n```\r\n2. 在路由配置中添加配置信息\r\n```javascript\r\nexport const UserFootprintRouter = {\r\n    state: 'user.footprint',\r\n    config: {\r\n        url: '/footprint',\r\n        views: {\r\n            'content@user': {\r\n                template: footPrintTpl,\r\n                controller: 'FootprintController',\r\n                controllerAs: 'vm'\r\n            },\r\n            'thumbList@user.footprint': {\r\n                template: thumbListTpl\r\n            },\r\n            'detailList@user.footprint': {\r\n                template: detailListTpl\r\n            }\r\n        },\r\n        title: '我的足迹'\r\n    }\r\n};\r\n```\r\n个人理解就是: viewname@statename去设置template\r\n\r\n#### 二、 $stateParams使用，^^最后一个点 \r\n先看代码：\r\n```javascript\r\nexport const AlbumDetailRouter = {\r\n    state: 'album.detail',\r\n    config: {\r\n        url: '/:id',\r\n        views: {\r\n            '@': {\r\n                template: albumDetailTpl,\r\n                controller: 'PhotoController',\r\n                controllerAs: 'vm'\r\n            }\r\n        },\r\n        title: '单张照片show'\r\n    }\r\n};\r\n```\r\n问: 我们经常会需要用到路由去传参,例如编辑一条信息,获取单个信息,应该如何去做呢?\r\n\r\n答: angular-ui-router提供了一个$stateParams的service,可直接获取.在controller中的使用示例\r\n```javascript\r\nexport default class PhotoController {\r\n\r\n    constructor(photoResource, $stateParams) {\r\n\r\n        let vm = this;\r\n\r\n        photoResource.success(data => {\r\n            vm.detail = data[$stateParams.id];\r\n        })\r\n    }\r\n}\r\n```\r\n有人肯定会疑问,$stateParams从何而来,在上面我们给angular.module中已经将其初始化,挂在到$rootScope.\r\n\r\n#### 三、这次真的是最后一个点了 most important: $urlRouterProvider\r\n1. when() for redirection\r\n```javascript\r\n    app.config(function($urlRouterProvider){\r\n        $urlRouterProvider.when('', '/index');\r\n    });\r\n```\r\n2. otherwise() for invalid routes\r\n```javascript\r\napp.config(function($urlRouterProvider){\r\n    $urlRouterProvider.otherwise('/home');\r\n});\r\n```\r\n###### it's over! 所有以上仅代表个人理解,如有不对,请指出,虚心接受改正错误!"},"comment":{"url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/issues/comments/233172429","html_url":"https://github.com/ShuyunXIANFESchool/FE-problem-collection/issues/5#issuecomment-233172429","issue_url":"https://api.github.com/repos/ShuyunXIANFESchool/FE-problem-collection/issues/5","id":233172429,"user":{"login":"hjzheng","id":4166657,"avatar_url":"https://avatars.githubusercontent.com/u/4166657?v=3","gravatar_id":"","url":"https://api.github.com/users/hjzheng","html_url":"https://github.com/hjzheng","followers_url":"https://api.github.com/users/hjzheng/followers","following_url":"https://api.github.com/users/hjzheng/following{/other_user}","gists_url":"https://api.github.com/users/hjzheng/gists{/gist_id}","starred_url":"https://api.github.com/users/hjzheng/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/hjzheng/subscriptions","organizations_url":"https://api.github.com/users/hjzheng/orgs","repos_url":"https://api.github.com/users/hjzheng/repos","events_url":"https://api.github.com/users/hjzheng/events{/privacy}","received_events_url":"https://api.github.com/users/hjzheng/received_events","type":"User","site_admin":false},"created_at":"2016-07-17T09:03:45Z","updated_at":"2016-07-17T09:03:45Z","body":"####  reslove 配置\r\n关于 路由中[配置 reslove以及它的好处](https://github.com/johnpapa/angular-styleguide/blob/master/a1/i18n/zh-CN.md#route-resolve-promises)\r\n\r\n举例:\r\n```js\r\n\t\t$stateProvider\r\n\t\t\t.state('home', {\r\n\t\t\t\turl: '/home',\r\n\t\t\t\ttemplateUrl: './partials/home.html',\r\n\t\t\t\tcontroller: 'HomeController',\r\n\t\t\t\tcontrollerAs: 'vm',\r\n\t\t\t\tresolve: {\r\n\t\t\t\t\trestaurants: function($http) { // 注意这里可以注入服务\r\n\t\t\t\t\t\treturn $http.get('data/restaurant.json').then(function(response) {\r\n\t\t\t\t\t\t\treturn response.data;\r\n\t\t\t\t\t\t}, function() {\r\n\t\t\t\t\t\t\treturn '服务器出错了, 请联系管理员';\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t})\r\n\r\n```"}}
{"actor":{"display_login":"hjzheng"}}