I have a simple route in my expressjs app configuration like -
app.get('/download/:noteid/:fileid',notes.download);
where notes.download is a function with the contents as -
exports.download = function(req,res) {
console.log("here");
console.log(req.params.noteid);
console.log(req.params.fileid);
};
now when i open directly in the browser the url -
http://localhost:5000/download/5f4815f2-73a9-4621-86ed-b4e302cc49ba/all
the i see the correct log in the server
but when i try something like -
Download
and then click on this download button angular takes me to a new page without any template defined for that page and i don't see anything in the logs of my server. so how do i make get requests like the one i make by directly entering in the url by the anchor element.
the route configuration for my angular app is something like this, in case if needed -
$routeProvider
.when('/', { templateUrl: '/partials/main/main', controller: 'mainCtrl'})
.when('/admin/users', { templateUrl: '/partials/admin/user-list',
controller: 'PaginationDemoCtrl'
})
.when('/browse/notes', { templateUrl: '/partials/notes/browseNotes',
controller: 'browseNotesCtrl', resolve:routeRoleChecks.user
})
.when('/upload/notes', { templateUrl: '/partials/notes/uploadNotes',
controller: 'uploadNotesCtrl', resolve:routeRoleChecks.user
})
.when('/profile',{ templateUrl:'/partials/account/mvProfile.jade',
controller: 'mvProfileCtrl' , resolve:routeRoleChecks.user
});
When you access the url directly from the address bar it does not go through the routeprovider while when u try to hit the url through the hyperlink(anchor tag) from your webapp , routeprovider checks if there is a path defined for your link.
You can remove the href and use the click event of the anchor tag which calls a function in the controller. This function must call $http module's get method with the url.
or --
add a path for in the routeprovider.
https://docs.angularjs.org/api/ng/service/$http#get
Related
I am creating an Angular.JS page inside of an ASP.NET MVC5 C# application, and I would like to remove the # and trailing path from the URL on a new page load or browser page refresh.
For example: www.example.com/calculator#/step2 I would like it to go back to simply www.example.com/calculator on a page refresh.
The idea is that I need it to start them back at the beginning of the calculator form on a new page load or a browser page refresh. The reason being is that the form I created does not persist the data between page refreshes, so they would need to refill in the data from the beginning.
Whenever the page is reloaded, it does call my ASP.NET calculator controller, so my idea is that the server could reset the URL path?
Inside of my ASP.NET calculator controller, I've got:
public class CalculatorController : Controller
{
// GET: Calculator
public ActionResult Index()
{
// check for # sign and remove it and trailing path from URL.
// or simply make the path "/calculator" every time.
return View();
}
}
Is there an easy way to do this? I am new to Angular.JS so if there is an Angular.JS solution to this problem I would love to hear that as well.
Using the advice of the helpful comments posted, I've written a solution to my question. Like davcs86 said, the string after the hash can only be handled client-side.
Using Angular.JS and resolve like charlietfl suggested, this is what I came up with:
var myApp = angular.module("app-calculator", ["calculatorControls", "ngRoute"])
.config(function ($routeProvider) {
$routeProvider.when("/", {
controller: "termsController",
controllerAs: "vm",
templateUrl: "/content/templates/termsView.html"
});
$routeProvider.when("/condition", {
controller: "conditionController",
controllerAs: "vm",
templateUrl: "/content/templates/conditionView.html",
resolve: {
validate: function ($location, Data) {
if (!Data.terms) {
$location.path('/');
}
}
}
});
$routeProvider.otherwise({ redirectTo: "/" });
});
Basically, I use the resolve: { validate: ... } section to check if my Data.terms field has been completed. If the value has not been set (in the case of a browser page refresh which resets the data), then it will send redirect back to the root page using $location.path('/');. Otherwise if the Data.terms has been set, then it will load the page requested.
I also solved this issue by jquery.My link was [http://localhost:53209/HarcamaIslemleri?toastMesaj=true] and I want to do it as
[http://localhost:53209/HarcamaIslemleri?toastMesaj=false] when I refresh the page.
in jquery I wrote this code block and it worked for me, I hope this answer will be useful
$(document).ready(function () {
const queryString = window.location.search;
if (queryString) {
const urlParams = new URLSearchParams(queryString);
const stepValue = urlParams.get('toastMesaj');
if (stepValue == "true") {
toastr.warning('Successfully Added!');
window.history.replaceState(null, null, '?toastMesaj=' + false);
}
}
});
I'm working on the routing of my angular application, but I can't seem to find the following:
example.com/#parameter
In this url the #parameter should stay #parameter and get the param data. Now it removes the # and goes to example.com/parameter
If I go to example.com/#parameter it should do the same as it would if I go to example.com/parameter
I have the following in my app.js
url: "/:bandName"
and send this data to my controller with $stateParams
Is there any way to keep the hashtag in the url ?
-- edit
so here is some code that works on enter with /#parameter
$urlRouterProvider.when(':#bandName', '/:bandName')
.otherwise('/');
$stateProvider.state('appband', {
url: "/:bandName",
templateUrl: "main.php",
controller: 'mainController'
})
$locationProvider.html5Mode(true);
With this if I go to example.com/#randomBandName I get redirected to example.com/randomBandNameand I get randomBandName as parameter in my controller
So what I need is on enter that example.com/#randomBandName stays example.com/#randomBandName and that I still get randomBandName in my controller.
But when I remove $urlRouterProvider.when(':#bandName', '/:bandName') I just get an empty page.
There are a few things that look suspect with this:
trailing slash
Are you using HTML5 mode for your URLs? I'd suggest using this URL setup url: "/parameter" if you indeed see param as more of a resource.
You might also read this - https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-make-a-trailing-slash-optional-for-all-routes
query param
If you are intending param to be a query parameter then you need this..
url: "/?parameter"
more on that here - https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters
I am working on an app that lets users create polls, then link that poll to other users for them to vote.
To let users give a direct link, I need two route parameters: the ID of the user who made the poll, and the poll question.
So I want to let users go to website.com/:id/:question, and then make the corresponding API get calls using those parameters to get the information.
However, the page always redirects to website.com/ no matter what is put in.
Any ideas of where I would go to change this?
EDIT://
The $routeParams seems to be the right idea!
However, I am having trouble making it work.
I set it up like so:
angular.module('voteApp')
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'index.html',
controller : 'MainCtrl'
})
.when ('/:id/:poll', {
templateUrl : 'index.html',
controller : 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Then the client side console keeps printing 'Tried to load angular more than once'
And when I switch the index.html to 'app/main/main.jade' it just prints the contents of that file.
I am fairly sure that the path to index.html is correct, since the path to main.jade is correct and I am basing the path to index.html relatively to that
If you are using NgRoute, you ought to use the $routeParams service: https://docs.angularjs.org/api/ngRoute/service/$routeParams
If you are using ui-Router, then you can use the $stateParams service: https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stateparams-1
You would also need to define a route/state to correspond to the path /:id/:question as well.
Learning Angular and running into an issue I cant seem to find a "good" answer to. I've been following the official Tutorial and have a similar setup with a project Im working on.
The $routeProvider .when case for phone details GETS a specific .JSON file based on the name of the phone clicked on in the phone list page. The problem is, if you type in a phone name that doesn't have a .JSON file associated with it, the route still proceeds and shows a blank page. I'm trying to figure out how to prevent this.
I've gotten as far as to add a resolve to .when route. However, I can only prevent the view from changing or use a $location.path redirect. Neither of these seem ideal.
How do I go about showing a "404 page" view for phone that doesn't have a JSON file? In my head, I would show a different templateUrl if the GET request responds with a 404, but cant seem to get it working.
Any help would be great!
Here is the code I've got so far:
My route handling.
.when('/game/:Game', {
templateUrl: 'views/game-detail.html',
controller: 'GameDetailCtrl',
resolve: {
myData: ["Games", "$location", "$q", "$timeout",'$rootScope', function(Games, $location, $q, $timeout,$rootScope) {
var def = $q.defer();
var path = $location.path().toString().substring(6);
// Games service
Games.get({gameName: path}, function(game, s) {
}).$promise.then(
function(data) {
// found game data
def.resolve(data);
},
function(error) {
// couldn't find JSON file
def.reject(error);
}
);
return def.promise;
}]
}
}).when('/pageNotFound', {
templateUrl: 'views/error.html'
})
Root Scope route change error listener:
$rootScope.$on("$routeChangeError",
function(event, current, previous, rejection) {
console.log("failed to change routes");
//$location.path('/pageNotFound');
});
Well, you really don't do it that way, what you would do in this case would be to have your template HTML contain the template for both the success and failure scenario and an ng-switch inside to flip states when the call fails or succeeds.
Also, I think it would work if you tried to copy the idea from directives as well:
Angular.js directive dynamic templateURL
You can try to change the path with the following code:
function(error) {
// couldn't find JSON file
$location.path('/pageNotFound');
}
I am developing a single page angular app.
The app takes a token off the URL, then passes it off to an API. Currently my URL looks like this:
www.example.com/?token=3d2b9bc55a85b641ce867edaac8a979173d4446525230290fc86a0ed8ff18b95
My code is already properly using angular routes, but I have to get the token off the URL like this:
var postToken = $location.search().token;
I have this on config:
app.config(function($locationProvider, $httpProvider, $routeProvider) {
$routeProvider
.when('/token/:token', {
templateUrl : 'views/select-token.html',
controller : 'selectHold'
})
.when('/purchase-hold/token/:token', {
templateUrl : 'views/purchase-token.html',
controller : 'purchaseHold'
});
});
I want my URL to be able to look like this:
www.example.com/token/3d2b9bc55a85b641ce867edaac8a979173d4446525230290fc86a0ed8ff18b95
What do I need to code to be able to search for a /token/ and grab the data next to it, as opposed to ?token= ?
Build your route like you currently are
.when('/token/:token', {templateUrl : 'views/select-token.html', controller : 'selectToken' })
Then in your controller inject in $routeParams and you will be able to access your route parameter
.controller('selectToken', function($scope, $routeParams){
$scope.token = $routeParams.token
}
you can inject $routeParams in your controller and it will be available in that
app.controller('selectToken', function($scope, $routeParams) {
console.log($routeParams.token);
// We now have access to the $routeParams here
});
then Angular will populate the $routeParams with the key of :token, and the value of key will be populated with the value of the loaded URL.
If the browser loads the URL www.example.com/token/3d2b9bc55a85b641ce867edaac8a979173d4446525230290fc86a0ed8ff18b95
,
then the $routeParams object will look like:
{ token: '3d2b9bc55a85b641ce867edaac8a979173d4446525230290fc86a0ed8ff18b95' }