CreativeZoller
CreativeZoller

Reputation: 306

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. 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

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? 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/

Upvotes: 1

Views: 119

Answers (1)

mohamedrias
mohamedrias

Reputation: 18566

In your controller, you've not injected $location that;s why it's showing $location is undefined.

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. When you want to have dynamic data in your URL you must use :itemLink as the pattern.

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

In your controller, you can get it using $stateParams

$stateParams.itemLink

Upvotes: 2

Related Questions