【问题标题】:How to get the value from URL parameter in AngularJS?如何从 AngularJS 中的 URL 参数中获取值?
【发布时间】:2014-11-17 13:52:58
【问题描述】:

我有一个类似http://example.com/test/sample&fname=hello&lname=world 的网址,它将显示一个名为“Home.html”的页面

我需要从 URL 中获取这些值 helloworld 并在相同的 'Home.html 中的 ng-init 指令中使用它'。

<div ng-init="init('val1','val2')"></div>

其中 val1 应该包含 helloval2 应该包含 world

是否可以在 AngularJS 中做到这一点,它是正确的方法吗?请帮帮我!

【问题讨论】:

  • 您不需要使用 ng-init,在控制器中使用 $routeParams 或 $location 并从那里设置范围值。

标签: angularjs angularjs-directive angularjs-scope angular-ui-router


【解决方案1】:

避免使用 ng-init 而使用控制器

function SomeController($scope, $location){
    var fname = $location.search().fname;    

}

【讨论】:

    【解决方案2】:

    使用 AngularJS,您可以使用 $location.search 读取查询字符串参数,如下所示:

    var init = function() {
        var val1 = $location.search()['val1'];
        var val2 = $location.search()['val2'];
        ...
    }
    

    【讨论】:

    • 似乎不适用于最新的 AngularJS
    猜你喜欢
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多