Why is $routeParams not working? Undefined - javascript

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.

Related

angular-ui-router only loads template but not controller not loaded

I tried to migrate my Angular app from using ngRoute to uiRoute. Everything works fine except the controllers. They simple don't load like they did with ngRoute and I don't get why. As I see it from uiRoute it should work like with ngRoute but it doesn't. There is no exception thrown. I also don't find any example for a similar configuration like mine although it's very simple. I home somebody can tell me where my controller is hiding.
http://plnkr.co/edit/VGyi3AxgslgpvwBCTkXI?p=preview
So as for ngRoute the controller should be accessible through 'homepage' but it looks like it's just empty :(
;(function(angular) {
'use strict';
angular
.module('MainRouter', ['ui.router'])
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('home', {
url: '',
views: {
"mainView": {
templateUrl: 'home.html'
}
},
controller: 'HomepageCtrl',
controllerAs: 'homepage'
});
}]);
})(angular);
When you use views option inside the state definition, then ui-router engine doesn't look for templateUrl & controller defined in state level, basically you need to provide controller & templateUrl value from the namedView definition only. In your case you should add controller in mainView definition object.
Code
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('home', {
url: '',
views: {
"mainView": {
templateUrl: 'home.html',
controller: 'HomepageCtrl',
controllerAs: 'homepage'
}
},
});
}]);
Demo Plunkr

How to globally implement Authentication with AngularJS, Devise and UI Router?

I'm quite new to Angular so this might be a newbie question.
I'm trying to implement a simple task manager (just an exercise) with Rails as backend and Angular as frontend. So far I followed a tutorial and everything worked fine.
Now I want to globally implement Authentication. That means: When a user is not registered and logged in, she should see a splash page or the login page.
I don't want to do that in every single Angular controller, because DRY. So I figured the UI Router might be a good place. And I have a slight suspicion that maybe $httpProvider.interceptors might be useful.
This is how far I got. I can check if a user is authenticated and prevent the page from loading. But nothing more. How would I go from here? Are there any good tutorials out there I missed?
This question on Stackoverflow goes in a similar direction but doesn't solve my problem since they are not using Devise.
Thanks!
// app.js
var app = angular.module("TaskManager", ['ui.router', 'templates', 'Devise'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/_home.html',
controller: 'MainCtrl',
resolve: {
projectPromise: ['projects', function(projects) {
console.log($rootScope);
return projects.getAll();
}]
}
})
.state('projects', {
url: '/projects/{id}',
templateUrl: 'projects/_projects.html',
controller: 'ProjectsCtrl',
resolve: {
project: ['$stateParams', 'projects', function($stateParams, projects) {
return projects.get($stateParams.id);
}]
}
})
.state('login', {
url: '/login',
templateUrl: 'auth/_login.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'Auth', function($state, Auth) {
Auth.currentUser().then(function() {
$state.go('home');
})
}]
})
.state('register', {
url: '/register',
templateUrl: 'auth/_register.html',
controller: 'AuthCtrl',
onEnter: ['$state', 'Auth', function($state, Auth) {
Auth.currentUser().then(function() {
$state.go('home');
})
}]
});
$urlRouterProvider.otherwise('home');
}
]);
// run blocks
app.run(function($rootScope, Auth) {
// you can inject any instance here
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
if(!Auth.isAuthenticated()) {
// So the magic should probably happen here. But how do I implement this?
// And how do I allow users to access the /login and /register page?
event.preventDefault();
}
})
});
I wrote an article that basically answers this question (at a high level at least) called How to Set Up Authentication with AngularJS and Ruby on Rails.
If you want to check whether the user is authenticated at any particular route, you can (in Angular's standard router, although I don't know about ui-router) use resolve. Here are a couple routes from an older project of mine:
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
isPublic: true
})
.when('/today', {
templateUrl: 'views/announcements.html',
controller: 'AnnouncementsCtrl',
resolve: {
auth: ['$auth', function($auth) {
return $auth.validateUser();
}]
}
})
The root route is public but /today requires authentication. Maybe that gives you enough to go on for ui-router as well. Side note: I should really update my article to account for ui-router (or Angular's new router) since I don't think many people use the regular old Angular router.
Edit: I remembered this thing from a different project of mine. This is CoffeeScript. Irrelevant code omitted.
"use strict"
angular.module("fooApp", [
"ngAnimate"
"ngCookies"
"ngResource"
"ngRoute"
"ngSanitize"
"ngTouch"
"ui.router"
"ng-token-auth"
])
.run ($rootScope, $auth, $location) ->
$rootScope.$on "auth:login-success", -> $location.path "/"
$rootScope.$on "auth:logout-success", -> $location.path "/sign-in"
$rootScope.$on "$stateChangeStart", (event, next) ->
$auth.validateUser().then (->
if $location.path() == "/"
$location.path "/file-uploads"
), ->
if !next.isPublic
$location.path "/sign-in"
Hopefully it's kind of self-evident what's going on there. This project DOES use ui-router, as you can tell from the $stateChangeStart.

Angularjs ng-view forbidden

i have the following routing:
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/site/pages/views/Admins/index.php'
}).
otherwise({
redirectTo: '/'
});
}])
however in my console i get the following:
GET http://example.com/site/pages/views/Admins/index.php 403 (Forbidden)
Can anyone tell me why this is happening?
I can tell you that i have given rights to both the view and the folder my angular project is to both Read, Write, Delete
Have you got any authentication on server side? It seems like your php code is validating request and returning response with code 403 (probably, not authenticated). What is the result when you paste http://example.com/site/pages/views/Admins/index.php in browser?
You can try attach controller, and then in controller make $http.get request and send proper data to backend to authenticate
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'basetpl.html',
controller: 'MyController'
}).
otherwise({
redirectTo: '/'
});
}])

Isn't Inline Array Annotation DI compatible with $routeProvider in AngularJS?

My codes looks like this
angular
.module('main', ['ngRoute'])
.config(['$routeProvider',
($routeProvider) ->
$routeProvider
.when '/',
templateUrl: 'homePage/homePage.html'
controller: 'MainCtrl'
])
angular.module('main').controller('MainCtrl',
['$scope' , ($scope) ->
$scope.test = {}])
The browser will compain Error: [ng:areq] Argument 'MainCtrl' is not a function, got Object.
But if I don't use the inline array dependency injection in MainCtrl and rewrite it like this:
angular.module('main').controller('MainCtrl',
($scope) ->
$scope.test = {})
Then everything works well. Does anyone have ideas about this? Thanks!
As the error message is very clear on the fact that issue is not with $routeProvider, You may want to restructure them. Also note that config block must have a function.
First create the module, then register the controller and config:
angular
.module('main', ['ngRoute']);
and then use it or chain through, i.e
angular.module("main", ["ngRoute"]).controller("MainCtrl", [
"$scope"
($scope) ->
return $scope.test = {}
]).config [
"$routeProvider"
($routeProvider) -> //Check this
return $routeProvider.when("/",
templateUrl: "homePage/homePage.html"
controller: "MainCtrl"
)
]
otherwise with the order of the script you have you are trying to create a controller on the app main before even it exists.
Also note that you need to include angular-router script as well.
Demo

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

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.

Categories

Resources