Reading url parameters in Angular JS [duplicate] - javascript

HTML source code
<div ng-app="">
<div ng-controller="test">
<div ng-address-bar browser="html5"></div>
<br><br>
$location.url() = {{$location.url()}}<br>
$location.search() = {{$location.search('keyword')}}<br>
$location.hash() = {{$location.hash()}}<br>
keyword valus is={{loc}} and ={{loc1}}
</div>
</div>
AngularJS source code
<script>
function test($scope, $location) {
$scope.$location = $location;
$scope.ur = $scope.$location.url('www.html.com/x.html?keyword=test#/x/u');
$scope.loc1 = $scope.$location.search().keyword ;
if($location.url().indexOf('keyword') > -1){
$scope.loc= $location.url().split('=')[1];
$scope.loc = $scope.loc.split("#")[0]
}
}
</script>
Here the variables loc and loc1 both return test as the result for the above URL. Is this the correct way?

I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller.
Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this:
$routeProvider.when('/view1/:param1/:param2', {
templateUrl: 'partials/partial1.html',
controller: 'MyCtrl1'
});
Then in your controller inject $routeParams:
.controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
...
}]);
With this approach you can use params with a url such as:
"http://www.example.com/view1/param1/param2"

While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location service, as injected in your own service or controller:
var paramValue = $location.search().myParam;
This simple syntax will work for http://example.com/path?myParam=paramValue. However, only if you configured the $locationProvider in the HTML 5 mode before:
$locationProvider.html5Mode(true);
Otherwise have a look at the http://example.com/#!/path?myParam=someValue "Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.

If you're using ngRoute, you can inject $routeParams into your controller
http://docs.angularjs.org/api/ngRoute/service/$routeParams
If you're using angular-ui-router, you can inject $stateParams
https://github.com/angular-ui/ui-router/wiki/URL-Routing

I found solution how to use $location.search() to get parameter from URL
first in URL u need put syntax " # " before parameter like this example
"http://www.example.com/page#?key=value"
and then in your controller u put $location in function and use $location.search() to get URL parameter for
.controller('yourController', ['$scope', function($scope, $location) {
var param1 = $location.search().param1; //Get parameter from URL
}]);

If the answers already posted didn't help, one can try with
$location.search().myParam;
with URLs http://example.domain#?myParam=paramValue

function GetURLParameter(parameter) {
var url;
var search;
var parsed;
var count;
var loop;
var searchPhrase;
url = window.location.href;
search = url.indexOf("?");
if (search < 0) {
return "";
}
searchPhrase = parameter + "=";
parsed = url.substr(search+1).split("&");
count = parsed.length;
for(loop=0;loop<count;loop++) {
if (parsed[loop].substr(0,searchPhrase.length)==searchPhrase) {
return decodeURI(parsed[loop].substr(searchPhrase.length));
}
}
return "";
}

Simple and easist way to get url value
First add # to url (e:g - test.html#key=value)
url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)
var url = window.location.href
(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")
url.split('=').pop()
output "stackoverflow"

When using angularjs with express
On my example I was using angularjs with express doing the routing so using $routeParams would mess up with my routing. I used the following code to get what I was expecting:
const getParameters = (temp, path) => {
const parameters = {};
const tempParts = temp.split('/');
const pathParts = path.split('/');
for (let i = 0; i < tempParts.length; i++) {
const element = tempParts[i];
if(element.startsWith(':')) {
const key = element.substring(1,element.length);
parameters[key] = pathParts[i];
}
}
return parameters;
};
This receives a URL template and the path of the given location. The I just call it with:
const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path());
Putting it all together my controller is:
.controller('TestController', ['$scope', function($scope, $window) {
const getParameters = (temp, path) => {
const parameters = {};
const tempParts = temp.split('/');
const pathParts = path.split('/');
for (let i = 0; i < tempParts.length; i++) {
const element = tempParts[i];
if(element.startsWith(':')) {
const key = element.substring(1,element.length);
parameters[key] = pathParts[i];
}
}
return parameters;
};
const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);
}]);
The result will be:
{ table: "users", id: "1", place_id: "43", interval: "week" }
Hope this helps someone out there!

in your router:
url: "/login/reset_password/:user/:token"
in your controller:
let userParam = $state.params.user
let tokenParam = $state.params.token

Related

How to get URL parameters in JavaScript?

I'm using Vue, but I'm not using vue-router.
How can I get URI parameters?
I found one way to get URI by using root el property.
But is there any proper way to get the parameters as I want to send them to
backend and get a response from server and display it.
You can get the URL parameters by using window.location.search:
const queryString = window.location.search;
console.log(queryString);
// ?product=troussers&color=black&newuser&size=s
For parsing parameters of the query string, use URLSearchParams:
const urlParams = new URLSearchParams(queryString);
For more info, read this tutorial.
Since you are not using vue-router, I don't think you'll be able to access your params. So your only chance is to use the URL api as:
const URL = new URL(window.location.href);
const getParam = URL.searchParams.get('foo');
This will give you the value of foo in ?foo=bar
Alternatively, you can do something like this.
new Vue({
el: '#app',
data () {
return {
params: window.location.href.substr(window.location.href.indexOf('?'))
}
},
methods: {
getParam (p) {
let param = new URLSearchParams(this.params);
if(param.has(p)){
return param.get(p)
}else{
false
}
}
},
})
Now, just get the param using getParam('foo')
We don't use vue router for the moment either. We use the following script to parse args.
var args = {};
var argString = window.location.hash;
//everything after src belongs as part of the url, not to be parsed
var argsAndSrc = argString.split(/src=/);
args["src"] = argsAndSrc[1];
//everything before src is args for this page.
var argArray = argsAndSrc[0].split("?");
for (var i = 0; i < argArray.length; i++) {
var nameVal = argArray[i].split("=");
//strip the hash
if (i == 0) {
var name = nameVal[0];
nameVal[0] = name.slice(1);
}
args[nameVal[0]] = decodeURI(nameVal[1]);
}
Route properties are present in this.$route.
this.$router is the instance of router object which gives the configuration of the router.
You can get the current route query using this.$route.query

Angular factory calling async factories randomly fails to execute

This factory is randomly failing to execute. JsonReader and ProgressTrack factories are both asynchronous - they read data from files, JsonReader returns a JSON object and ProgressTrack returns an integer, which I use to certain extract data from the JSON object.
While debugging, I think I made the code slow enough that it ran correctly 100% of the time, which leads the to believe I'm not properly waiting for data to be loaded before I start handling it.
If anyone can point out any obvious problem with my code, I'd be very grateful.
Maybe I need to write a promise for both factories and chain them, before handling data from both?
angular.module('prgBr', [])
.factory('PrgBr', ['JsonReader', 'ProgressTrack', '$q', function(JsonReader, ProgressTrack, $q) {
var prgbr = {};
prgbr.getPrg = function() {
var defer = $q.defer();
JsonReader.get(function(data){
ProgressTrack.getProgress(function(progress) {
var currentEx = progress;
var chapEx = progress - 1;
var currentChap = data.exercises[chapEx].chapter;
var currentTest = data.exercises[currentEx].str1;
function arraypush(f) {
var chapterarray = [];
var idarray = [];
chapterarray.push(data.exercises.filter(function(elem) {
return elem.chapter===f;
}));
var idarray = chapterarray[0].map(c=>c.id)
var chapexnumber = idarray.length;
var exindex = idarray.indexOf(currentEx) + 1;
var progbarval = (exindex/chapexnumber)*100;
var progbarvalpercent = progbarval + "%";
var prgres = {a: progbarval,b: progbarvalpercent};
defer.resolve(prgres);
};
arraypush(currentChap);
});
});
return defer.promise;
}
return prgbr;
}]);
JsonReader is:
angular.module('jsonReader', ['ngResource'])
.factory('JsonReader', function($resource) {
return $resource('resources.json');
});

Clearing a page and reloading a controller?

So I have a small angular app that takes in a search query, sends it to an elasticsearch node I've got set up, and then displays the result set on screen.
My problem is that when I make a new query, the results gets appended to the end of the current result set. What I would like it to do is to erase whatever is currently on the page, and reload it with only the new data, much like how searching for something on Google returns a completely new set of results.
Is there any way to do this? Code below for reference.
// this is the controller that displays the reuslts.
var displayController = function($scope, $rootScope, $window, notifyingService) {
var dataReady = function(event, data) {
$scope.resultSet = notifyingService.getData();
}
$rootScope.$on('data-ready', dataReady)
}
app.controller("displayController", ["$scope", "$rootScope", "$window", "notifyingService", displayController]);
// this is the service that's responsible for setting the data
var notifyingService = function($http, $rootScope) {
var svc = {
_data: [],
setData: setData,
getData: getData
};
function getData() {
return svc._data;
}
function setData(data) {
var base_obj = data.hits.hits
console.log("Setting data to passed in data.");
console.log('length of dataset: ' + base_obj.length);
for(var i = 0; i < base_obj.length; i++){
svc._data.push(base_obj[i]._source);
}
$rootScope.$broadcast('data-ready', svc._data);
}
return svc;
};
app.factory("notifyingService", ["$http", "$rootScope", notifyingService]);
In setData just before the loop re-initialize svc._data
svc._data = [];
Clear you svc._data before you start adding the new query.
function setData(data) {
var base_obj = data.hits.hits;
svc._data = [];//reset your array before you populate it again.
for(var i = 0; i < base_obj.length; i++){
svc._data.push(base_obj[i]._source);
}
$rootScope.$broadcast('data-ready', svc._data);
}

Routing using RESOLVE does not wait on complete result to start with second reolve function

Still new to AngularJS , I have following situation...Which I'm looking for a solution ...
When the APP is loaded (before any screen is shown) - I need to load following (in a fixed order as shown in the list):
.properties file and store the properties to a ARRAY
REST service method to get all translations labels to be used in the application
Because the properties file will contain for example connection properties, it's important this properties file is loaded & parsed before proceeding with the app...
Using the $routeProvider I've used following to work with the 'resolve' approach:
// routing
app.config(function($routeProvider) {
$routeProvider
// login
.when('/', {
templateUrl : 'pages/login.html',
controller : 'loginController',
resolve:{
// load properties
loadProperties: function(properties){
return properties.initProperties();
},
// load labels
loadLocalization: function(localize, properties){
console.log(properties.getProperties());
return localize.initLocalizedResources();
}
}
})
// dashboard
.when('/dashboard', {
templateUrl : 'pages/login.html'
})
});
The 'initLocalizedResources' method:
initLocalizedResources: function(){
if (!localize.loadedFromRest){
localize.loading = true;
//$localStorage.restServer = "http://localhost:8084";
// var restServer = properties.getProperty('restServer') + '/WebSDPServiceMobileAPI/i18n/i18nlabels_get/culture/';
var restServer = 'http://localhost:3034';
var restServer = restServer + '/WebSDPServiceMobileAPI/i18n/i18nlabels_get/culture/';
var culture = 'en-gb';
if ($localStorage.language !== undefined)
culture = $localStorage.language.culture;
var restCall = restServer + culture;
logMessage(' - Localize - callRestServer called - : ' + restCall);
return $http.get(restCall)
.success(localize.successCallback)
.error(function(data, status){
// set the flag to keep from looping in init
localize.loadedFromRest = false;
localize.loading = false;
});
}
},
The 'properties' service:
app.factory('properties', function($http){
var arrProperties = [];
return {
getProperties: function(){
return arrProperties;
},
getProperty: function(key){
return arrProperties[key];
},
addProperty: function(key, value){
console.log('add property : ' + key + ' - ' + value);
arrProperties[key] = value;
},
initProperties: function(){
return $http.get('serviceapp.properties').then(function (response) {
var props = response.data.split("\n");
for (var i = 0, len = props.length; i < len; i++) {
var value = props[i].split("=");
arrProperties[value[0]] = value[1];
}
console.log(arrProperties);
});
}
};
});
But what I notice is that the order of the Resolve is not the correct order...
When logging the properties inside the initLocalizedResources method, they are still []... While logging the 'properties' inside the loginControllerthey are correctly filled with data... But at a stage too far...
What I need to accomplish is to load the properties before the localization labels (REST)...
My ideas of workaround:
Add an extra route for loading the properties, and when completing navigating to the second route, where it will load the localization, then continue to the /login route
Manually bootstrap the AngularJS application after loading & parsing the properties
As mentioned, these feel and are workarounds, ...
Is there anybody with any other ideas / tips or any help?
Thanks
I believe you can do it like this:
resolve:{
// load properties
loadProperties: function(properties){
return properties.initProperties();
},
// load labels
loadLocalization: function(localize, properties, loadProperties){
console.log(properties.getProperties());
return localize.initLocalizedResources();
}
}
Notice, how the second resolve is dependent on the loadProperties resolve.
https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c

angularjs read from properties file

In angularJS how can I read a value from a properties file?
connection.properties:
url="http://localhost:8080"
user= "me"
get= "GET"
post= "POST"
app.js:
var app = angular.module('testing',[]);
app.controller('testCtrl',function($scope,$http) {
$http({
url: connection.properties.url ,
method: connection.properties.get,
params: {user: connection.properties.user})
});
});
If connection.properties is a file that lives on your web server, then you simply need to do this:
var app = angular.module('app', []);
app.controller('test', function ($scope, $http) {
$http.get('connection.properties').then(function (response) {
console.log('a is ', response.data.a);
console.log('b is ', response.data.b);
});
});
You can see an example here:
http://plnkr.co/edit/3Ne3roFOwcfVmg2mgnUr?p=preview
Simple way is to
create a js file named
"config.js" (lets assume in the path scripts/config/config.js)
config.js:
var test1="http://testurl.com"
var test2="globalconstant"
In the html page include this config.js at the top (above the main
controller.js): **<script..
src="./scripts/config/config.js"></st>**
In the controller make the following change:
MainController.js:
$scope.appUrl = test1;
$scope.appConstant = test2;
Langdon's answer loads the content of the properties file for me but the value inside the properties are not accessible to me in the format of response.data.a and response.data.b etc and always returns undefined. For the value to be available to me I have to extract the content of the properties file and to turn them into JSON format before I can use it. A modification of the above proposed solution would be such:
var app = angular.module('app', []);
app.controller('test', function ($scope, $http) {
function extractProperties(data){
const lines = data.split("\n");
properties = {}
for (const l of lines) {
const line = l.trim();
if (!line || line[0] === '#') {
continue;
}
const keyValue = line.split("=");
const key = keyValue[0].trim();
const value = keyValue[1].trim();
properties[key] = value
}
return properties;
}
$http.get('connection.properties').then(function (response) {
const properties = extractProperties(response.data);
console.log('URL is ', properties.url);
console.log('User is ', properties.user);
});
});

Categories