angular中ng-route和ng-ui-router的差异

作者: 三杯两盏淡茶 | 来源:发表于2017-03-09 10:14 被阅读0次

    ngroute和ui-router并不是两个相互独立的部分,ui-router是社区库提供的用来提高ngroute的功能的,可用于多视图(嵌套),功能十分强大!

    为了全面的了解两者的不同点,在这里我就加上$http请求时对两者进行比较,

    1.引入文件:

    ngroute:<script src="angular-route.js"></script>

    ui-router:<script src="angular-ui-router.js"></script>

    2.注入:

    ngroute: var app = angular.module('app',['ngRoute']);

    ui-router: var app = angular.module('app',['ui.router']);

    3.配置:

    【传参控制、判断条件、默认指定】

        $routeProvider.when('/index/:id',{
            templateUrl:'template/musicList_tpl.html',
            controller:"musicControler"
        }).otherwise({
            redirectTo:'/index/1'//redirectTo
        })
    ]}
    
    ui-router:app.config(['$stateProvider','$urlRouterProvider',function ($stateProvider,$urlRouterProvider) {
            $stateProvider.state("first",{//(first命名空间 绑定到视图可以也放在a标签)
    多种传递参数方式:
                url:'/index/:id',//(这才是hash值)
                //url:'/index/{id:int}',
                //url:'/index/?id&name',
                templateUrl:"me-musicList.html",
    
    可以拥有自身的控制器
                controller:"lrxController"
            })
                .state('music',{
                    url:'/music/:id',
                    templateUrl:"me-musicList.html",
                    controller:"lrxController"
                })
            //(router网页默认指定首页)   
            $urlRouterProvider.otherwise('index/1');
    
    4.控制器:【依赖:$routeParams'、'$stateParams'、回调:success/error、then/catch】
    
    ngroute: app.controller('lrxController',['$routeParams','$http','$scope',function ($routeParams,$http,$scope) {//
    //        console.log($routeParams.id);
            $http({
                url:'listMusic.php',
                method:'get',
                params:{
                    id:$routeParams.id
                }
            }).success(function (res) {
                $scope.musicList = res;
            })
        }]);
    
     
    
    ui-router: app.controller('lrxController',['$scope','$stateParams',"$http",function ($scope,$stateParams,$http) {
        $http({
            url: "listMusic.php",
            method: "get",
            params: {
                id: $stateParams.id
            }
        }).then(function (res) {//success替换成then
            console.log(res);
            $scope.musicList = res
        })
    }]);
    
    5.指令和视图:【参数,ng-view。 ui-sref、 ui-view】
    
     a href="#/index/1">流行</a>
    a href="#/index/2">复古</a>
    
    <div class="content" ng-view> </div>
    
     
    
    <!--(ui-sref-active查看当前激活状态并设置Class)
    .active a{
        font-size: 30px;
    }-->
    
     
    
    <li ui-sref-active="active"><a  ui-sref="home({id:1})">首页</a></li>
    <li ui-sref-active="active" ui-sref="music({id:2})"><a音乐</a></li>
    
    <div class="content" ui-view> </div>

    相关文章

      网友评论

        本文标题:angular中ng-route和ng-ui-router的差异

        本文链接:https://www.haomeiwen.com/subject/ddkwgttx.html