Access URL parameters in Angularjs in the Controller

五迷三道 提交于 2019-12-24 00:09:45

问题


How to access the URL parameters through the angularJS controller. For example: i would like to read parameter1 and parameter2 in a controller so that i can take appropriate action in my controller. http://localhost:8080/MyApplication?Parameter1=testresponse&parameter2=1234


回答1:


After spending some time, i figured that $location is the one I was searching for. Below is sample code snippet. >>AngularJS v1.4.8

main.js

     var mainApp = angular.module("app",['ui.bootstrap','ngModal']);
    mainApp.config(['$locationProvider',function($locationProvider){    
        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
        });

    var mainController = function($scope,$window,$rootScope, $cookies,$cookieStore,$location){
var searchObject = $location.search();

    window.alert("parameter is :.."+searchObject.param1);
    window.alert("Url typed in the browser is: "+$location.absUrl());
    }

    mainApp.controller("MainController",["$scope","$window","$rootScope",'$location',mainController]);

Enter the this URL in the browser: http://localhost:8180/Application/#param1=test

Output:

alert 1: parameter is :.. test

alert 2: "Url typed in the browser is: " +http://localhost:8180/Application/#param1=test




回答2:


Inject $routeParams in your controller like

angular.module(yourapp).controller(yourcontroller,['$routeParams',
function($routeParams){
    console.log($routeParams.Parameter1) //Prints test response
    }]);



回答3:


Using $routeParams service you can access url params. In your case

angular.module('myApp', [])
 .controller('myController', (function ($scope, $routeParams) {
   $routeParams.Parameter1 // for 1st param
   $routeParams.parameter2 // for second param
});    

For more information - $routeParams



来源:https://stackoverflow.com/questions/36573129/access-url-parameters-in-angularjs-in-the-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!