reading param from the current url in AngularJS - angularjs

Yes there are alot of questions been asked about this topic. But I couldn't get solution for my problem.
Here is my url
http://localhost/resetpassword.html/7f18114f-1e1b-4c73-bf0f-f9e6f5bbb293
And user will be able to get this screen just by clicking the link provided by email. I have tried using $routeParams, $location.search() but can't find my param.
I am using nodejs as my web server. From the server side routing I have added the following route to handle the request.
app.get('/resetpassword.html/:resetcode', function (req, res) {
console.log("reset code: " + req.params.resetcode);
//res.render('resetpassword.html/' + req.params.resetcode);
res.render('resetpassword.html', { resetcode: req.params.resetcode });
});
And my angular configurations as follows
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', { templateUrl: 'home.html' })
.when('/resetpassword.html/:resetcode', { templateUrl: '/resetpassword.html', controller: 'ResetPasswordCtrl' })
.otherwise({ redirectTo: '/' })
;
$locationProvider.html5Mode(true);
})
I can access the path from $location so I can parse for the query string. But is that the only way I have?
Thanks

I believe what you are looking for is RouteParams
http://docs.angularjs.org/api/ngRoute.$routeParams

You have to configure your route like this to be able to use $routeParams:
$routeProvider.when('/resetpassword.html/:resetcode', /**route**/);
Then you should be able to get the reset code using $routeParams.resetcode.

Related

Simple AngularJS routing not working properly

For some reason, I can't seem to route to the add screen. What am I doing wrong? Here's my app.js
var moviesApp = angular.module('moviesApp', ['ngRoute']);
moviesApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/home.html',
controller: 'MoviesController'
})
.when('/add', {
templateUrl: 'partials/add.html',
controller: 'MoviesController'
})
.when('/edit', {
templateUrl: 'partials/edit.html',
controller: 'MoviesController'
});
});
Here's the anchor tag:
Add Movie
Which is contained within my home.html template which is a part of index.html.
The app doesn't crash...it just doesn't do anything.
Any thoughts on what I'm doing wrong?
It may be because of the change in the default hash-prefix in angularjs version 1.6. What you have written works in the given context: Proof
You can confirm this is the case by changing:
Add Movie
to:
Add Movie
If it works look at for possible solutions at:
AngularJS: ngRoute Not Working
If you want to make i behave as you expect (version 1.5) you could choose soultion 3 from the link:
3. Go back to old behaviour from 1.5 - set hash prefix manually
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
set up a route start event to help debug the problem
.run(function ($rootScope) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
console.log(event);
console.log(current);
console.log(next);
console.log('$routeChangeStart: ' + next.originalPath)
});
});
just add this to the end of your route config
Just as a side note I would use a state provider over a route provider. State providers let you define a hierarchy. It's a little harder to work with but much more flexible.

Retrieve userId from url with AngularJs

I'm learning AngularJs at present and I've hit a brick wall due to my lack of knowledge on it.
What I'm trying to do is pass in a Id (guid) within the URL and inside my controller I'll retrieve it and pass it to a WebApi to return some data linked to that Id.
However I'm unable to get the route correct, my currently URL looks like this:
http://localhost:15216/
When I pass in the Id it will look something like this
http://localhost:15216/573637
Quite straight forward, my page is called index.html, after browsing the web and looking at this question and basically replicating what he/she has provided I'm still unable to retrieve the value from my URL.
This is my current configuration:
var myApp = angular.module('christmasvip', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/:userId', { templateUrl: '/index.html', controller: 'mainController' }).
otherwise({ redirectTo: '/index.html' });
}]);
And this is my Controller:
myApp.controller("mainController", function ($scope, $http, $routeParams) {
var userId = $routeParams.userId;
alert(userId);
});
I then manipulate the URL so it would look like :
http://localhost:15216/573637
But when I alert the userId it say's "underfined"
I've also included angular-route.js in my project
Any help/solution would be great.
In the documentation of ngRoute you can find an example... Try using the URL: http://localhost:15216/index.html#/573637
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
Can you try the url
http://localhost:15216/#/573637
I assume your root is http://localhost:15216/
your confusing the $routeProvider in the config you say
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/:userId', { templateUrl: '/index.html', controller:'mainController' }).
so your telling it, "if we see any url like this '/anything' take 'anything' and supply it as a parameter to the $routeParam service
then you add
otherwise({ redirectTo: '/index.html' });
which tells it, if you get any other url redirect to "/index.html", but index.html is something so its going to want to route you to '/' with the route param as 'index.html'
also you need to make sure you have <ng-view></ng-view> inside of your index.html file for the $routeProvider to load the route correctly, that is probably your main issue, but the first thing i mentioned would probably be an error once you add it.

Passing routing from Express to Angular, Angular not picking up the redirect

In my Express file, I have:
app.all('*', function(req, res) {
res.redirect('/#' + req.originalUrl);
});
Yeah, I know — the code above will cause a redirect loop but isn't this where Angular is supposed to come to the rescue like so:
$routeProvider
.when('/', {
templateUrl: 'ui/books/index.html',
controller: 'BooksController'
})
.otherwise({
templateUrl: 'ui/x_partials/error.html'
});
My intention is that, if an URL like /non-existent-page is provided, Express redirects it to Angular — res.redirect('/#' + req.originalUrl) — resulting in an URL like #/non-existent-page. Since this route hasn't been accommodated by my $routeProvider, I'm expecting ng-view to serve templateUrl: 'ui/x_partials/error.html'
But this approach isn't working! How do I get Angular to pick up the redirect from Express?
Please advise.

Authentication and Routing with Express/Passport, AngularJS and ensureLoggedIn not working on "/" url

I have a MEAN stack app generated with the Yeoman Generator Angular Fullstack generator. You should only have access to the site by logging in.
The repo for ensureLoggedIn is here
While logged out, if I try to navigate to '/products' I'm redirected to '/login' just fine. However, I'm having an issue redirecting users who aren't logged in when the url is '/' or even 'localhost:9000' without the slash.
If I'm not logged in, and at the login screen, and I modify '/login' to just '/' or '' I'm sent to "main" in AngularJS and treated as logged in(I'm assuming because it recognizes the session?) and able to click links through to '/products' or '/users'.
My current routes.js looks like this:
/**
* Main application routes
*/
'use strict';
var errors = require('./components/errors');
var auth = require('./controllers/auth');
var passport = require('passport');
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;
module.exports = function(app) {
// Insert routes below
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*').get(errors[404]);
app.route('/login').get(auth.login).post(auth.loginUser);
app.route('/logout').get(auth.logout);
// All other routes should redirect to the index.html
app.all('*', ensureLoggedIn('/login'));
app.route('/*').get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
};
I've also tried this with the routes:
app.route('/*').get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
Which seems to have the same behavior as placing ensureLoggedIn in app.all.
Here's a snippet of my routing on the Angular side, which uses ui-router:
.config ($stateProvider, $urlRouterProvider, $locationProvider) ->
$httpProvider.interceptors.push('httpInterceptor')
$urlRouterProvider
.otherwise '/'
$stateProvider
.state 'main',
url: '/'
templateUrl: 'app/views/main/main.html'
controller: 'MainCtrl'
.state 'users',
url: '/users'
templateUrl: 'app/views/users/index.html'
controller: 'UsersController'
As I said, the redirect works fine on '/users'. I'm not sure if this is a routing issue or auth issue. Auth should be fine, since clicking logout does take you to login screen and restricts access, but doesn't restrict access to the '/' route.
For the views, the login.jade is actually on the server side and the form is processed there. Except for a 404.jade, all other views are on the client-side and served using ui-router.
I feel like I'm overlooking something basic. Or just don't fully understand how this is working together. Any help would be great.
EDIT:
One thing I tried was changing the routing before app.route('login'):
app.route('/')
.get(function(req, res) {
res.render('login');
});
And changing ui-router url for main from '/' to '/main'.
This still grabbed index.html from angular and logged me in, so it didn't work. I also tried res.redirect to login in routes.js and it didn't redirect.
This is the code I use for handling authentication. It is a hack but I didn't find a better way when I needed to code it. Also the routes defined in the system varied user to user so I couldn't define them in the normal config stage. This may help with your issue though.
$routeProvider
.when("/login", { templateUrl: "/view/account/login.html", controller: Login })
.when("/forgottenpassword", { templateUrl: "/view/account/forgottenpassword.html", controller: ForgottenPassword })
.otherwise({ redirectTo: "login" });
This basically only allows access to 2 views. Once someone authenticates successfully I rebuild the routing table with the new valid views. Any invalid navigation goes to the login view.
I do this through a hack though so it might not be the best implementation angularjs wise. I do this by keeping a reference to $routeProvider on the window object then use $routeProvider as normal when you have a successful logon.
The original $routeProvider provided in angular also needs a public method to clear the existing routes before adding new ones.
After
var routes = {};
Add
this.ClearRoutes = function ()
{
routes = {};
}
Example usage after successful logon
$routeProvider.ClearRoutes();
$routeProvider
.when("/home", { templateUrl: "/view/home.html", controller: Home })
.when("/logoff", { templateUrl: "/view/account/logoff.html", controller: Logoff })
.otherwise({ redirectTo: "home" });

Unable to refresh page when using Angular, jQM, and Adapter

I'm working on a web page that is using Angular, jQuery Mobile, and the jQuery Mobile Angular adapter by tigbro. I have everything up an running and it works great except for one issue and that is if at any point if you refresh the page using the browser's refresh button it will give a 404 error as if it doesn't understand the route anymore. I'm not sure where the issue might be since it gets a little confusing with the two frameworks and the adapter working together and I'm new to all of these technologies.
IE happens to be the only browser this doesn't happen in and the difference seems to be in the url. Here is what it looks like when you browse to a page in IE:
http://site.com/SalesManagement/SalesManagementIndex.aspx#!/ViewNotes/4
Here is what it looks like when you browse to the same page in another browser like Chrome:
http://site.com/SalesManagement/ViewNotes/4
If you go to the first url in Chrome it will load the page and then rewrite the url to the 2nd one.
Below is my routing configuration:
var SalesManagementApp = angular.module('SalesManagementApp', [])
SalesManagementApp.config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {
$routeProvider
.when('/Search', { templateUrl: 'Views/GrowerSearchView.aspx' })
.when('/SearchResults', { templateUrl: 'Views/GrowerResultsView.aspx' })
.when('/ViewNotes/:growerIndexKey', { templateUrl: 'Views/NotesHistoryView.aspx' })
.when('/EditNote/:growerIndexKey/:noteIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/AddNote/:growerIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/', { templateUrl: 'Views/GrowerSearchView.aspx' })
.otherwise({ templateUrl: 'Views/GrowerSearchView.aspx' });
} ]);
I've read some about html5 mode verse hashbang mode but setting html5 mode to off or on in the configuration just made my routing not work at all. Any help would be much appreciated.
I figured this out thanks to a similar question on the github site for the adapter: https://github.com/opitzconsulting/jquery-mobile-angular-adapter/issues/163
The fix for this is to disable html5Mode in angular and prefix your links with the # character. This makes your urls a little uglier as you are no longer using the html5 history API but in my case that doesn't matter. Optionally you can specify a hash prefix (by default it seems to be !) but I set mine to empty string. I couldn't find any documentation telling me why this is useful but its important to know what the prefix is so you can properly set your links.
Below is my updated routing configuration. Notice I now inject the $locationProvider.
var SalesManagementApp = angular.module('SalesManagementApp', [])
SalesManagementApp.config(['$routeProvider', '$compileProvider', '$locationProvider', function ($routeProvider, $compileProvider, $locationProvider) {
$locationProvider.html5Mode(false).hashPrefix("");
$routeProvider
.when('/Search', { templateUrl: 'Views/GrowerSearchView.aspx' })
.when('/SearchResults', { templateUrl: 'Views/GrowerResultsView.aspx' })
.when('/ViewNotes/:growerIndexKey', { templateUrl: 'Views/NotesHistoryView.aspx' })
.when('/EditNote/:growerIndexKey/:noteIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/AddNote/:growerIndexKey', { templateUrl: 'Views/UpsertNoteView.aspx' })
.when('/', { templateUrl: 'Views/GrowerSearchView.aspx' })
.otherwise({ templateUrl: 'Views/GrowerSearchView.aspx' }); // jQuery Mobile seems to ignore the / and just use .otherwise.
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
if (!localStorage.SessionInfo)
window.location = '/Login.aspx';
} ]);
My links now look like: #/ViewNotes/{{growerIndexKey}}

Resources