代码之家  ›  专栏  ›  技术社区  ›  Saqib Ali

如何将参数传递到Angularjs的路由器ui而不显示在URL中?

  •  1
  • Saqib Ali  · 技术社区  · 6 年前

    我有一个AngularJS应用程序 ui-router 管理我的应用程序的状态和URL路由。

    .state('my_state', {
        url: '/my_state/:arg1',
        templateUrl: 'http://www.example.com/html/my_file.html',
        controller: 'MyCtrl'
    })
    

    这是它的控制器:

    app.controller('MyCtrl', function($stateParams) {
        console.log('arg1 = ', $stateParams.arg1)     
    );
    

    以下是我如何从另一个控制器中向其发送人员:

    $state.go('my_state', {'arg1': 'hello'});
    

    $state.go /my_state/hello 我在浏览器的调试窗口中看到以下内容:

    arg1 = hello
    

    现在我的问题是:我能给这个控制器添加另一个参数吗

    1. arg2 .
    2. 如果提供,可以在内部访问 MyCtrl

    如果是,请告诉我怎么做。

    4 回复  |  直到 6 年前
        1
  •  1
  •   Amirhossein Mehrvarzi GGregson    6 年前

    默认情况下,UI路由器中的路由参数是可选的。 arg1 是一个 参数。所以两者都是 /my_state/:arg1 /my_state/ 可以,但不行 /my_state arg1

    .state('my_state', {
        url: '/my_state/:arg1',
        templateUrl: 'http://www.example.com/html/my_file.html',
        controller: 'MyCtrl'
    })
    

    您可以添加

    .state('my_state', {
        url: '/my_state/:arg1',
        templateUrl: 'http://www.example.com/html/my_file.html',
        controller: 'MyCtrl',
        params: {
            arg2: { value: null }
        }
    })
    

    你必须在 params .

    请注意 squash 财产(内部) 参数 当前参数值与默认值相同时 . 如果未设置挤压,则使用配置的默认挤压策略。

    Working Plunker

    更新

    Working Plunker 它使用 $state.go('my_state', {'arg1': 'hello', 'arg2': 'world'}); 内部控制器。

    两者之间没有功能上的区别 ui-sref $state.go 对于 Activating a state

        2
  •  1
  •   joshbang    6 年前
    .state('someState', {
                url: '/my_state?arg1',
                templateUrl: 'http://www.example.com/html/my_file.html', // I assume this is correct for the way you set it up.
                controller: 'MyCtrl',
                params: { // This is the part you'll add
                    arg2: {
                        value: null, // you can set a default value
                        squash: true
                    }
                }
    })
    

    这应该对你有用!我已经用了很多次了!非常有用。

        3
  •  0
  •   holydragon    6 年前

    试试这个:

    .state('my_state', {
        url: '/my_state',
        templateUrl: 'http://www.example.com/html/my_file.html',
        controller: 'MyCtrl',
        params: null
    })
    
        4
  •  0
  •   hannad rehman    6 年前
    Using Parameters without Specifying Them in State URLs
    

    即使参数没有出现在url中,您仍然可以指定要接收的参数。您需要在状态中添加一个新字段params,并按照在链接中使用参数中指定的方式创建链接

    例如,你有一个州。

    .state('contacts', {
            url: "/contacts",
            params: {
                param1: null
            },
            templateUrl: 'contacts.html'
        })
    

    您创建的链接是

    <a ui-sref="contacts({param1: value1})">View Contacts</a>
    

    $state.go() 我也是。

    $state.go('contacts', {param1: value1})