$routeProvider.when(..) not catching all URLs - javascript

setup: jade, angular, express, node.
In my routeProvider of angular, I am having some issues. I am requesting a url with a parameter which it is not catching.
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
//... omitted some url/pages here
//start of SPA
.when('/dashboard/', {
templateUrl: 'partials/index',
controller: 'dashIndexCtrl'
})
.when('/dashboard/class/:id',{
templateUrl: 'partials/class',
controller: 'classCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
When I call localhost/dashboard/class/TEST
I get redirected to root.
I declare my routes on the server side as follows:
app.get('/dashboard', routes.dashboard);
app.get('/dashboard/partials/:name', routes.partials);
app.get('/api/class/:id', api.classGet);
My controller name matches up with the routeProvider. In which case the controller code goes as follows:
app.controller('classCtrl', function($scope, $http, $routeParams){
$http.get('/api/class/' + $routeParams.id)
.success(function(dataJson){
console.log(dataJson);
});
});
Why is routeProvider missing this url? I have set breakpoints within my controller so I am certain it is not being called. Also my partials/class.jade is not being called. Let me know if you need anymore code or directory information. Thanks in advance.
After further investigation:
If I go: localhost/dashboard/partials/class it will load that jade file. So it is definitely the controller.
Directory structure, I believe this is my issue now....
+---\
| +---\views
| +---index.jade
| +---dashboard.jade
| +---\partials
| +---index.jade
| +---class.jade

Take a look into console and observe that AngularJS tries to load templates from /partials/index then from /dashboard/partials/index
Solution
set templateUrl path as /dashboard/partials/index in config section.
Reason: angular-route.js
templateUrl = $sce.getTrustedResourceUrl(templateUrl);
if (angular.isDefined(templateUrl)) {
next.loadedTemplateUrl = templateUrl;
template = $http.get(templateUrl, {cache: $templateCache}).
then(function(response) { return response.data; });
}
There is no concatenation templateUrl with route path – just load tempalteUrl from Angular root of application.

Related

$locationProvider.html5Mode(true) not working with tomcat

I am trying to remove "#" from the URL of my Angular JS app. It is currently deployed on tomcat server on my location machine and accessible through a custom port like :8081.
I looked at various articles and also different threads on stackoverflow to fix the issue. But all went in vain.
I am getting following error (from developer console of the browser) when I try to access the home page of my app using localhost:8081/myAngularApp.
Uncaught Error: [$injector:modulerr] Failed to instantiate module myAngularApp due to:
TypeError: Cannot read property 'html5Mode' of undefined
at http://localhost:8081/myAngularApp/js/angularMyApp.js:34:31
.....
.....
If I remove $locationProvider.html5Mode({...}); then I am able to access the application with a hash like http://localhost:8081/myAngularApp/#/
Here is the snippet from my JS file which configures Angular Module (myAppMain.js) :
...
...
myAngularApp.config([ '$routeProvider', '$locationProvider',
function($routeProvider, $routeParams, $locationProvider) {
$routeProvider
// route for the login page
.when('/login', {
templateUrl : 'pages/login.html',
controller : 'loginController'
})
// route for the dashboard page
.when('/dashboard', {
templateUrl : 'pages/dashboard.html',
controller : 'dashboardController'
});
// route for the FAQ page
.when('/faq', {
templateUrl : 'pages/faq.html',
controller : 'faqController'
})
// route for the About us page
.when('/aboutUs', {
templateUrl : 'pages/aboutUs.html',
controller : 'aboutUsController'
});
.otherwise({redirectTo: '/'
});
if(window.history && window.history.pushState){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
}
]);
...
...
I have already added base href="/" tag in the head tag of index.html.
I am not sure if I have to do some changes at tomcat end to make it working or there is some other problem..
Please help.
Thanks
myAngularApp.config([ '$routeProvider', '$locationProvider', function($routeProvider, $routeParams, $locationProvider) {
should be
myAngularApp.config([ '$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

Why is $routeParams not working? Undefined

I'm triyng to build simple applications on Angular and Django rest framework.
I have a next root app:
app.js
angular
.module('sharePhotoApp', [
'ngRoute',
'sharePhotoApp.controllers',
'sharePhotoApp.services'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/',
controller: 'PostListController'
})
.when('/:username', {
templateUrl: '/user/',
controller: 'UserDetailController'
})
.otherwise({
redirectTo: '/'
});
}]);
And the next controller:
angular
.module('sharePhotoApp.controllers')
.controller('UserDetailController', UserDetailController)
UserDetailController.$inject = ['$scope','$routeParams','userService'];
function UserDetailController($scope, $routeParams, userService){
alert($routeParams.username);
$scope.user = userService.get({ username: $routeParams.username });
}
I tried to follow the next URL in browser: http://127.0.0.1:8000/user/#/admin
I suppose in this case should triggered route with username parameter.
But I've gotten undefined.
Could anyone explain where I done mistake?
"Note that the $routeParams are only updated after a route change
completes successfully. This means that you cannot rely on
$routeParams being correct in route resolve functions. Instead you can
use $route.current.params to access the new route's parameters."
https://docs.angularjs.org/api/ngRoute/service/$routeParams
Have you also installed ngRoute module?
As the description says, the route is not finished in your controller, so the params are also undefined.
$scope.$on('$routeChangeSuccess', function() {
// $routeParams should be populated here
});
should do the work.

AngularJS Routing Not Working As Expected

I'm new to AngularJS and very lost at this point. I am trying to learn from this code:
http://plnkr.co/edit/dd8Nk9PDFotCQu4yrnDg?p=preview
script.js:
// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
My index.html file includes
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
I have it set up on a local environment. I can load the main page but the routing only changes the URL, nothing else. Any ideas what could be causing this?
When you say only Url is called and page is not rendered means, ngroute works fine. One thing you need to make sure is that all html files reside under pages directory.
Also there should be <ng-view> tag inside index.html page
The best example is the plunker you are referring to.
I found the solution to my problem. I had to add
app.use(express.static(__dirname ));
To my node server script. I don't understand why this was needed, though.

How to use url parameters in angularjs, ui-router and $stateParams

I have followed the instructions from https://github.com/angular-ui/ui-router/wiki/URL-Routing
but cannot get this to work properly.
I have the following:
var application = angular.module('application', ['ui.router']);
application.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise("/test");
$stateProvider
.state('index', {
url: "/test/:param",
templateUrl: "App/Test.html",
controller: function ($scope, $stateParams) {
alert($stateParams.param);
}
});
$locationProvider.html5Mode(true);
});
Without the /:param this works as you would expect - i.e. the ui-view is correctly populated with Test.html. However, whenever I put the /:param in I get an error. The error is:
GET http://localhost:3880/test/App/Test.html 404 (Not Found)
App is the route of my angular stuff and Test.html should have a path of
http://localhost:3880/App/Test.html
which it does if not trying /:param. However, when trying /:param you can see that there is an extra /test/ in the path before /App.
Please someone help, as I would like to consume the parameter in the controller once it is correct.
You URL for this route should be like this : http://localhost:3880/test/app Where app is param.
Use absolute path for templateUrl. relative url wont work.
templateUrl: "/path/to/App/Test.html",

AngularJS relative url routing issue

I have my backend web framework loading my AngularJS app with following URL
http://localhost/New/Alpha/App
I also have it set up so that anything after App will still load the same thing
http://localhost/New/Alpha/App/home
http://localhost/New/Alpha/App/settings
...
I'm trying to make my AngularJS app to work in the way that it would pick up the bit of URL after App and load a controller/template accordingly. I have a problem with routing in my AngularJS app though
var main = angular.module("main", ["ui.bootstrap", "ngRoute"]);
main.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("home", {
templateUrl: "assets/tpl/home.html",
controller: "mainController"
})
.otherwise({
redirectTo: "fail"
});
$locationProvider.html5Mode(true);
});
main.controller("mainController", function($scope) {
console.log("home")
});
If I try this URL
http://localhost/New/Alpha/App/home
it changes the URL to
http://localhost/fail
instead of leaving the URL as it is and loading the template/controller. If however I change the config and give it a full relative URL it does work as supposed to
.when("/New/Alpha/App/home", {
templateUrl: "assets/tpl/home.html",
controller: "mainController"
})
My problem is, that the part of URL before App - /New/Alpha cannot be hardcoded in. It could be /New/Beta, /New/Gamma, etc.
Is what I want to do possible at all without hardcoding the full relative URL match?
UPDATE Sorry, forgot to mention that the number of URL segments before App can change, as in it could be /New/Beta/App and it also could be /New/Another/Beta/App. I don't suppose something like */App or /New/*/App is possible instead of /New/:placeholder/App?
Will this work for you?
var main = angular.module("main", ["ui.bootstrap", "ngRoute"]);
main.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/New/:greek/App/home", {
templateUrl: "assets/tpl/home.html",
controller: "mainController"
})
.otherwise({
redirectTo: "fail"
});
$locationProvider.html5Mode(true);
});
main.controller("mainController", function($scope) {
console.log("home")
});
You could then retrieve the greek with $routeParams.greek from within your controller.
The general solution to this problem is to have the server pass the app URL to your client-side code. In other words, use server-side code to dynamically write the equivalent of the following on the page:
var appUrl = '/New/Alpha/App';
Then setting up the route provider becomes:
main.config(function($routeProvider, $locationProvider) {
$routeProvider
.when(appUrl + "/home", {
templateUrl: "/assets/tpl/home.html",
controller: "mainController"
})
.otherwise({
redirectTo: appUrl + "/fail"
});
$locationProvider.html5Mode(true);
});
That way the knowledge of the application base URL lives in one place — server-side (which makes sense as only the server is in a position to truly know, if you think about it).
In your specific case, if the application base URL is implicit in the URL structure, you could calculate the following client-side:
var appUrl = window.location.pathname.match(/^\/New\/.*\/App/);
Needs work, but you get the idea. Then you can set up the route provider exactly as above.

Categories

Resources