0

I want to redirect to another web page when I click a button. Please find the following code

js

app.controller('myCtrl', ['$scope', '$location', function($scope, $location) {

$scope.redirect = function()
{
console.log($location.url());

};

}

I can obtain the current url using $location.url() which is follows

http://IP:Port/?myId=this-is-my-test-page

What I want to do is i want to redirect to the following page when i click a button

http://IP:Port/?myId=this-is-my-test-page2

I want to edit the existing url inside the controller without hard coding the whole url as IP and Port can be changed. How can I achieve this?

Although I used $location.path("http://IP:Port/?myId=this-is-my-test-page2"); What is does is it appends to the current url as follows

http://IP:Port/?myId=this-is-my-test-page2#http://IP:Port/?myId=this-is-my-test-page2

How can I redirect to the required page ?

tharindu
  • 513
  • 6
  • 26
  • You might want to refer to the [documentation](https://angular.io/tutorial/toh-pt5#add-a-navigation-link-routerlink) of Angular. I think you should define [routes](https://angular.io/tutorial/toh-pt5#add-routes). – Barrosy Apr 26 '19 at 09:17
  • Can I see the routes? – nadun Apr 26 '19 at 09:39
  • I haven't created any routes. Can't I do this without using routes? – tharindu Apr 26 '19 at 09:41

3 Answers3

0

I had a not so similar issue where I had to convert the variable to a string and then modify the string. Then convert back to the proper data type.

Mike Guerin
  • 141
  • 5
  • I have the created url but I am unable to redirect to the page when the button is clicked – tharindu Apr 26 '19 at 09:40
  • Are you unable to get the onclick to redirect or is it that the url is incorrect. http://IP:Port/?myId=this-is-my-test-page2#http://IP:Port/?myId=this-is-my-test-page2 instead of just "http://IP:Port/?myid=this-is-my-test-page2"? – Mike Guerin Apr 26 '19 at 17:46
0

Angular has its own routing. Everything right of # is the Angular routing (client side routing). Everything to the left of the # sign is your MVC/WebApi routing (server side routing). This is the essence of a single page application.

If you want to change the server side routing you need to do the redirect on the server side, so do a request to the server to change the url. If you want to change the client side (Angular) routing you need to use the "$location.path('')" in your angular code. Be aware that you cannot change anything to the left of the # sign on the client side.

You are trying to change the server side piece of the url, so you need to do a request to the server to change the url.

See this question for more information about the two:

Jeroen VL
  • 341
  • 5
  • 9
0

I tried using $window.location and it was successful. Non of the other methods worked.

app.controller('myCtrl', ['$scope', '$window', function($scope, $window) {

$scope.redirect = function()
{
$window.location = "http://IP:Port/......";

};

}
tharindu
  • 513
  • 6
  • 26