I wrap the href to URL, and try to remove one component, remove with delete, but component does not disappear. Do you know why?
let url = new URL(window.location.href);
let p = url.searchParams['postId'+$(".selected").length];
delete p;
window.location = url.toString();
I tried this:
const filteredItems = url.searchParams.filter(key => url.searchParams[key] == postID);
let key = filteredItems.keys.first;
url.searchParams.delete(key);
but it says
Uncaught TypeError: url.searchParams.filter is not a function
I tried now this expression, but filter does not work, do you have any idea why?
function togglePost(postID) {
let url = new URL(window.location.href);
const filteredItems = Object.keys(url.searchParams).filter(key =>
url.searchParams[key] == postID
);
let key = filteredItems.keys.first;
The delete operator deletes properties from objects.
You are trying to delete a variable. This fails silently.
To delete something from a URLSearchParams object, use the delete method:
let url = new URL('http://example.com/foo.cgi?a=1&b=2');
console.log(url.toString());
url.searchParams.delete('a');
console.log(url.toString());
Let's say I have an object that contains the values:
const pathParams = { schoolId :'12', classroomId: 'j3'}
and I have a path: school/:schoolId/classroom/:classroomId
I would like to extract: 'schoolId' and 'classroomId' from the path so that I can later replace them with their corresponding values from the pathParams object. Rather than iterating from the pathParam object keys, I want to do the other way around, check what keys the path needs and then check their values in the object.
I currently have this:
function addPathParams(path, paramsMap) {
const pathParamsRegex = /(:[a-zA-Z]+)/g;
const params = path.match(pathParamsRegex); // eg. school/:schoolId/classroom/:classroomId -> [':schoolId', ':classroomId']
console.log('--params--', params)
let url = path;
params.forEach((param) => {
const paramKey = param.substring(1); // remove ':'
url = addPathParam(url, param, paramsMap[paramKey]);
});
return url;
}
function addPathParam(path, param, value) {
return path.replace(`${param}`, value);
}
Does this look robust enough to you? Is there any other case I should be considering?
Here's a couple of tests I did:
Result:
I want to add a base url and query parameters to each link:
function buildURL(relativePath) {
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
return url.toString();
}
It works fine for most cases:
buildURL('search')
"http://example.com/search?utm_source=app"
buildURL('search?q=query&page=2')
"http://example.com/search?q=query&page=2&utm_source=app"
The problem starts when I add an anchor:
buildURL('search#anchor')
"http://example.com/search?utm_source=app#anchor"
buildURL('search#anchor?q=query')
"http://example.com/search?utm_source=app#anchor?q=query"
This is not a valid URL with an anchor.
Any ideas on how to overcome that using URL?
EDIT
The expected outcome is adding the query params after the anchor
buildURL('search#anchor')
"http://example.com/search#anchor?utm_source=app"
buildURL('search#anchor?q=query')
"http://example.com/search#anchor?utm_source=app?q=query"
function buildURL(relativePath) {
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
Don't pass in a hash in the search params.
But if you must, you can detect the hash, split it from the parameter, set the search param and add the hash
function buildURL(relativePath) {
var hash = "";
if (relativePath.indexOf("#")!=-1) {
var parts = relativePath.split("#");
hash = encodeURIComponent(parts[1]); // optionally handle ? in the hash part
relativePath=parts[0];
}
var url = new URL('http://example.com/' + relativePath);
url.searchParams.set('utm_source', 'app');
if (hash) url.hash=hash;
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
This should work.. Pass the hash after the query params
function buildURL(path) {
var relativePath = path.split('#')
var url = new URL('http://example.com/' + relativePath[0]);
url.searchParams.set('utm_source', 'app');
url.hash = relativePath[1] ? relativePath[1] : ''
return url.toString();
}
console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
console.log(buildURL("searchr?q=query&q2=query2#anchor"));
I have a function prototype that loads data from a path. The trick is that I need to change the path afterward. I tried call, apply, bind and even assign but as I am a novice I did not find the solution.
Here a sample of my code :
Chat.prototype.loadMessages = function() {
this.messagesRef = this.database;
var setMessage = function(data) {
var val = data.val();
this.displayMessage(data.key, val.name, val.text);
}.bind(this);
};
var chat = new Chat
function setPath (newpath) {
chat.loadMessages.messageRef = newpath; // I guess, it is where I'm wrong...
chat.loadMessages(); // It should load messages from the new path in my chat container.
}
As I said I also tried :
chat.loadMessages.call(newpath);
or
var setPath = function(newpath) {
chat.loadMessages(newpath);
}.bind(chat);
setPath();
chat.loadMessages();
But the chat container continues to disclose messages from the old path...
This looks a bit convoluted. Just pass messagesRef as a parameter and make it default to this.database:
Chat.prototype.loadMessages = function(messagesRef = this.database) {
// do whatever is needed with messagesRef
};
chat = new Chat();
chat.loadMessages(); // load from the default location
chat.loadMessages('foobar'); // load from this specific location
It looks like you are creating a function with loadMessages, which is fine but you need to pass in a value to set the new path. Is this more of what you were thinking?
Chat.prototype.loadMessages = function (newPath) {
this.messagesRef = newPath || this.database; // if newPath is empty than default to this.database
var setMessage = function(data) {
var val = data.val();
this.displayMessage(data.key, val.name, val.text);
};
var chat = new Chat
function setPath (newpath) {
chat.loadMessages(newpath);
}
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