Get url parameter via Angularjs

Asked

Viewed 258 times

1

Well, I need to get a parameter from mine url as soon as my page is loaded.

localhost/123456

The parameter would be: 123456

Using $Location, I got the full url, but I couldn’t get the parameter I need to be loaded into my controller

 myApp.controller('Controller', function ($scope, traineeControlService, $location) {

var vm = this;
//getAll();

$scope.numberOfregistrationUser = {};

var searchObj = $location.url();

  console.log(searchObj);
}

1 answer

2

One way would be to use the ngRoute. Through the $routeProvider can configure the routes of your site, and with this extract the parameters of the Urls and inject them directly into your controller.

That is to say:

var myApp = angular.module('app', ['ngRoute']); // adicione o ngRoute como modulo do seu modulo

myApp.config(function($routeProvider) {

    // indica que quando tiver uma URL do tipo http://localhost/[id], que deve utilizar este template e controlador
    $routeProvider.when('/:id', {

        templateUrl: '[caminho para a sua pagina HTML]',
        controller: 'Controller' // nome do seu controlador
    }); 
})

myApp.controller('Controller', function ($scope, traineeControlService, $routeParams) {

    var vm = this;
    //getAll();
    $scope.numberOfregistrationUser = {};
    // var searchObj = $location.url();

    console.log($routeParams.id);
}

The object $routeParams contains all parameters defined in the URL (note when the URL is configured, use of the : to indicate that a parameter should be read).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.