您的位置:首页 > Web前端 > AngularJS

Angular 学习笔记 5

2014-12-09 13:58 381 查看
这篇和下一篇将介绍 ui-router。
https://github.com/angular-ui/ui-router
为什么使用这个而不使用 angular 原生的 router 呢?

因为项目已经用这个了。

依赖。



ui-router 创造了 state 的概念,我的第一反应是多此一举,

然后用着用着感觉还行。

例子1 basic state

var state = "hi, everyone!";

    angular.module('myApp', ['ui.router'])
            .config(function ($stateProvider) {
                $stateProvider
                        .state(state, {
                            url: '/hello',
                            template: '<div>{{showState()}}</div>',
                            controller: function ($scope) {
                                $scope.showState = function () {
                                    return state
                                }
                            }
                        })
            })
    ;
<div ng-app="myApp">
    <div ui-view>This div will be replaced.</div>
</div>



直接访问是不行的,需要加上 #hello,这就是路由。



例子2 three ways to change state

改变 state 或 route 的方法有三,最直接的就是改变访问的 url。

另外两种就是利用 ui-serf directive 或 $state 服务。

angular.module('myApp', ['ui.router'])
            .config(function ($stateProvider) {
                $stateProvider
                        .state('state1', {
                            url: '/state1',
                            template: '<div ui-sref="state2">go to state2</div>' +
                            '<div ng-click="goToState2()">another way to state2</div>',
                            controller: function ($scope, $state) {
                                $scope.goToState2 = function () {
                                    $state.go('state2');
                                };
                            }
                        })
                        .state('state2', {
                            url: '/state2',
                            template: '<div ui-sref="state1">go to state1</div>'
                        })
            })
    ;
<div ng-app="myApp">
    <div ui-view>This div will be replaced.</div>
</div>


例子3 $stateParams
有时候需要用到 url 中的部分路径作为参数,

这是就可以使用 $stateParams 服务了。

angular.module('myApp', ['ui.router'])
            .config(function ($stateProvider) {
                $stateProvider
                        .state('state', {
                            url: '/state/:index',
                            template: '<div>{{person}}</div>',
                            controller: function ($scope, $stateParams) {
                                var personList = [
                                    "Linda",
                                    "Mike",
                                    "John"
                                ];
                                $scope.person = personList[$stateParams.index - 1]
                            }
                        })
            })
    ;
<div ng-app="myApp">
    <div ui-view>This div will be replaced.</div>
</div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: