简体   繁体   English

从Angular中的网址获取参数

[英]Get parameter from the url in Angular

Well I have a problem. 好吧,我有一个问题。 I am using now a factory to handle dtas for two controllers in my app. 我现在正在使用工厂来处理应用程序中两个控制器的dta。 When I click to a link, it routes me to another view with a specific url, which last tag I want to reuse, so I'm trying to slice it like 当我单击链接时,它会将我路由到具有特定URL的另一个视图,我想重用最后一个标记,因此我尝试将其切片

window.location.pathname.split("/").slice(-1)[0]

but it seems to be not working, and saying: $location is undefined :/ Anyone ideas on how to solve this? 但它似乎不起作用,并说:$ location是未定义的://关于解决此问题的任何想法? Maybe a trivial error what I made but... the more eyes sees more :) 也许是我犯的一个小错误,但是……更多的眼睛看到了更多:)

portApp.controller("itemController", ["$scope", "workFactory",
    function($scope, workFactory, $stateParams) {

        console.log(window.location.pathname.split("/").slice(-1)[0]);
        $location.path(); // it says $location is undefined in the console

        var newpath = $stateParams.itemLink;
        $scope.onViewLoad = function(){
            console.log(newpath);
        };
    }
]);

Here is the jsfiddle for it - https://jsfiddle.net/d5bjrjov/ 这是它的jsfiddle- https: //jsfiddle.net/d5bjrjov/

In your controller, you've not injected $location that;s why it's showing $location is undefined. 在您的控制器中,您没有注入$location ;这就是为什么它显示$location是不确定的。

portApp.controller("itemController", ["$scope", "workFactory",
    function($scope, workFactory, $stateParams) {

must be 一定是

portApp.controller("itemController", ["$scope", "workFactory", '$stateParams', '$location',
    function($scope, workFactory, $stateParams, $location) {

In your State Provider 在您的国家提供者中

You have 你有

 .state('items', {
                url: '/items/{itemLink}',
                controller: 'itemController'
            });

The URL pattern is wrong. URL模式错误。 When you want to have dynamic data in your URL you must use :itemLink as the pattern. 如果要在URL中包含动态数据,则必须使用:itemLink作为模式。

 .state('items', {
                    url: '/items/:itemLink',
                    controller: 'itemController'
                });

In your controller, you can get it using $stateParams 在您的控制器中,您可以使用$stateParams获取它

$stateParams.itemLink

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM