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.
Related
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.
I have an Angulrjs application and in the app.js I have the following config like below:
.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider
.otherwise({
redirectTo: '/'
});
I am using ng-route and in my app.js run function I call a backend API which redirects me to a login page and once I enter my credentials it calls back the UI on the following address
http://hostname.company.net/?token=24OzjW%2FKZVfkiV%2Bku22T0ag%3D%3D
Now the page is blank instead of routing to the /. I have mapped the / with MainController but the controller and view is not getting mapped. If I print the $location.path the value is /.
Even if I reload the screen, the page is blank. Only when I remove the ?token=... and hit refresh I am getting the screen.
If I change the url to anything else, then it is working fine. If the route is a valid url, then corresponding controllers/view is called else MainController/MainView is getting called.
My config entry for handling the / is like below:
$routeProvider
.when('/', {
templateUrl: 'app/main/main.html',
controller: 'MainCtrl',
resolve: {
message: function (authService) {
return authService.authenticateUser();
}
}
});
Please let me know where I am going wrong or how to proceed as I am completely clueless on this bug.
EDIT: Removed incorrect information to avoid any potential misleading.
Keeping this here for now due to comment thread.
Using Angular I have a dozen or so routes setup similar to the following example code.
Is there a way to override which template and controller is loaded based on some other criteria while keeping the URL in tact? My goal is to display a login page when... lets say $scope.isLoggedIn = false. I don't want to change the URL to /login.
SomeApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/place', {
templateUrl: 'routes/place.html',
controller: 'PlaceCtrl'
})
.when('/test', {
templateUrl: 'routes/test.html',
controller: 'TestCtrl'
});
}]);
ngRoute is a very simple library that can basically only maps urls to controller/views. If you want more flexibility, try ui-router which has the ability to route based on state.
This isn't really doable with ngRoute, but with ui-router you can dynamically provide different templates based on just about anything you want.
$stateProvider.state('root',
url: '/'
controller: 'HomePageController'
templateProvider: [
'$rootScope'
'$templateCache'
'$http'
($rootScope, $templateCache, $http) ->
templateId = if $rootScope.isLoggedIn then "home-page-logged-in" else "home-page-not-logged-in"
templateId = "/templates/#{templateId}.html"
return $http.get(templateId, cache: $templateCache)
]
)
The catch is, as far as I know, you can't change the controller, only the template. Which kinda stinks.
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.
I'm just starting out with Angular, so this might be a common newbie mistake but I am trying to achieve the following url format:
http://myapp.localhost/index.html#!/about
Which I believe should be the default for Angular?
This is my configuration:
angular.module('App', []).config(function($routeProvider, $locationProvider, VIEWS_ROOT) {
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix = '!';
// Routing
$routeProvider.when('/', {templateUrl: './welcome.html', controller: 'WelcomeController'});
$routeProvider.when('/about', {templateUrl: './about.html', controller: 'AboutController'});
})
.run(function($rootScope) {
//...
});
In my html I have a simple anchor like so:
About
However when I click that anchor, the resulting URL constructed is:
http://myapp.localhost/index.html#/!/about
Which obviously fails to match any of my routes... a bit stumped on what's actually happening here, or what I'm doing wrong. I'm running off my local Apache instance under a vhost. There's nothing going on with mod_rewrite - so it looks like Angular is doing this.
It's a method to set the hashPrefix, not a property. $locationProvider.hashPrefix('!');