如何在Angular UI-ROUTER中使用不同的参数模式定义URL

时间:2015-12-14 17:43:34

标签: angularjs url angular-ui-router

我是Angular UI-ROUTER的新手,我想知道如何定义相同的URL,但使用不同的参数组合,如:

$stateProvider
    .state("no_param",{
        url: "/param",
        /* if no param, goes here*/
        template: "<div ng-repeat='p in params'>{{p}}</div>",
        controller: function($scope, $stateParams){
            $scope.params = $stateParams;
        }
    })
    .state("one_param",{
        url: "/param?param1",
        /* if one param1, goes here*/
        template: "<div ng-repeat='p in params'>{{p}}</div>",
        controller: function($scope, $stateParams){
            $scope.params = $stateParams;
        }
    })
    .state("another_one_param",{
        url: "/param?param2",
        /* if one param2, goes here*/
        template: "<div ng-repeat='p in params'>{{p}}</div>",
        controller: function($scope, $stateParams){
            $scope.params = $stateParams;
        }
    })
    .state("two_param",{
        url: "/param?param1&param2",
        /* if param1 & param2, goes here*/
        template: "<div ng-repeat='p in params'>{{p}}</div>",
        controller: function($scope, $stateParams){
            $scope.params = $stateParams;
        }
    })

我尝试了这个,但它不起作用。没有显示,只显示空白页。

然后我在控制器内部设置一个断点,当我导航到像/param?param2=test

这样的网址时,控制器永远不会运行

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您缺少的是views属性,这是一个工作示例:

JSFiddle

angular.module('myApp', ['ui.state'])
    .config(['$stateProvider', '$routeProvider',
        function($stateProvider, $routeProvider) {
            $stateProvider
                .state('test', {
                    url: '/test',
                    views: {
                        'main': {
                            template: '<a ng-href="#/test/hello">param1</a> - <a ng-href="#/test/hello/world">param2</a>',
                        }
                    }
                })
                .state('one_param', {
                    url: '/test/:param1',
                    views: {
                        'main': {
                            template: '<a ng-href="#/test">home</a> <div ng-repeat="p in params">{{p}}</div>',
                            controller: function($scope, $stateParams) {
                                $scope.params = $stateParams;
                            }
                        }
                    }
                })
                .state('two_param', {
                    url: '/test/:param1/:param2',
                    views: {
                        'main': {
                            template: '<a ng-href="#/test">home</a> <div ng-repeat="p in params">{{p}}</div>',
                            controller: function($scope, $stateParams) {
                                $scope.params = $stateParams;
                            }
                        }
                    }
                });
        }
    ]);