How do you access route parameters in an AngularJs Controller - javascript

I have a simple angular example where I can not get the route paramters for the query string in the URL. How do I do this?
Controller:
appRoot.controller('RegistrationController', ['$scope', '$resource', '$routeParams', function ($scope, $resource, $routeParams) {
if ($routeParams)
debugger;
}]);
Main Configuration File
var appRoot = angular.module('registrationApp', ['ngRoute', 'registration.directives', 'ngResource']); //Define the main module + dependancies
//Sets up AngularJS module and routes and any other config objects
appRoot
.config(['$routeProvider', function ($routeProvider) {
//Setup routes to load partial templates from server. TemplateUrl is the location for the server view (Razor .cshtml view) - Frigin amaze-balls
$routeProvider
.when('/registration/:inviteToken', { templateUrl: 'registration', controller: 'RegistrationController' })
.otherwise({ redirectTo: '/home' });
}])
.controller('RootController', ['$scope', '$route', '$routeParams', '$location', function ($scope, $route, $routeParams, $location) {
$scope.$on('$routeChangeSuccess', function (e, current, previous) {
$scope.activeViewPath = $location.path();
});
}]);
When I browse to something like http://example.org/registration/?inviteToken=2354234 route paramters is alway an empty object. I have also tried http://example.org/registration#/?inviteToken=2354234
One thing maybe worth noting is that http://example.org/registration is the MVC controller
Can someone help me understand what I'm doing wrong?

In your configuration, you have specified a route like this:
http://example.org/#/registration/2354234
(where $routeParams.inviteToken will be 2354234)
If you want to match a URL like this http://example.org/registration/?inviteToken=2354234, then you need a different route:
/registration/?inviteToken=:inviteToken
I am not usre you are aware of this, but the routes you define refer to the path after the #, unless you are using (and have configured correctly both on the client-side and on the server-side) "HTML 5" mode.

Related

Error: ng:areq Bad Argument AngularJS

I am working on a new portfolio site and want to use AngularJS to display my work and pure css to format layout etc.
I found a useful tutorial that outlined how to structure your app for future scaling and have set up a file tree like so:
so each component is a basically a mini MVC. I have set up my routes in app.routes.js and organised app.module.js as below:
app.module.js:
angular.module('app', ['ngRoute', 'appControllers', 'appResources']);
angular.module('appControllers', ['ngRoute']);
angular.module('appResources', ['ngResource']);
app.route.js:
angular.module('app')
.config(['$routeProvider', function ($routeProvider) {
'use strict';
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'app/components/home/home-view.html',
controller : 'HomeCtrl'
})
// route for the about page
.when('/about', {
templateUrl : 'app/components/about/about-view.html',
controller : 'AboutCtrl'
})
// route for the contact page
.when('/contact', {
templateUrl : 'app/components/contact/contact-view.html',
controller : 'ContactCtrl'
});
}]);
so this is my set up, for now, I just need to see that each controller for the routes are working and then I will begin adding in my content, but I have hit a hurdle straight away as the controllers for each view are showing as undefined.
Here is an example of a controller, they are all the same at the moment, but with a different message:
angular.module('appControllers')
.controller('AboutCtrl', ['$scope', '$http', function ($scope, $http) {
'use strict';
$scope.message = 'This will be the about page';
}]);
the html is correct and there are no typos, so I am scratching my head as to why this is showing up as an error.
Is this something to do with the way I have my modules set up?
Any assistance would be greatly appreciated.
Many thanks in advance.
This error is telling you that your HomeCtrl is undefined. You will need to include a <script src="app/components/home/HomeController.js"></script> in your index.html file to include each of your controllers with this type of app configuration.
If you want to avoid this, you can scaffold your app something like this.
(function () {
"use strict";
angular.module('appControllers')
.controller('HomeCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.message = 'This will be the home page';
}])
.controller('AboutCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.message = 'This will be the about page';
}]);
})();
There is no single "best" way to do something. It is all relative to the needs of your app and preference.

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 - Error controller is not a function, got undefined

This is a very common problem apparently when declaring multiple controllers but every fix on this forum that I tried to follow or somewhere else, didn't seem to work (probably am missing something).
I have app.js file and 3 separate controller files and a services file.
I used one of the controllers and everything worked fine. Now I am trying to redirect to another view which handled by ProfileManagement controller, but it is showing the error:
Error: [ng:areq] Argument 'ProfileManagementController' is not a
function, got undefined
This is what I have in the beginning of each controller file and also app.js...
app.js:
var app = angular.module('starter', ['ionic', 'starter.controllers', 'starter.services']);
app.run(function($ionicPlatform) {...
and in app.js, I am using this route before the error shows:
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'ProfileManagementController'
}
}
})
My controllers are here...
UserAccessController:
app.controller('UserAccessController', ['$scope', '$http', '$state', '$q', '$rootScope', 'CreateUserService', 'UserObjectService', function($scope, $http, $state, $q, $rootScope, CreateUserService, UserObjectService){
and ProfileManagementController:
app.controller('ProfileManagementController', ['$scope', '$http', function($scope, $http){
}]);
Also with tabs project template of ionic framework, I got the file controller.js by default where I commented all controllers but left the first line:
angular.module('starter.controllers', []);
//.controller('ProfileController', function($scope) {})
//
//.controller('OrdersController', function($scope) {
//
//})
//
//.controller('MoreOptionsController', function($scope, $stateParams) {
//
//})
//
//.controller('ConnectionsController', function($scope) {
//
//});
What am I doing wrong here that leads to the error message? (the view actually associated with the route tabs.home actually loads but the console shows the error.
Thanks,
You probably forgot to add the script tag to define your controller within the html.
for example:
<script src="yourController.js"></script>

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

AngularJS: Error when injecting $modal inside a controller that is nested inside of a directive

We have a custom directive that generates html around a checkbox. This uses transclusion to inject the contents that are passed within it. It looks something like this:
somecheckbox.js
angular.module('namespace.directives')
.directive('someCheckbox', function() {
return {
templateUrl: 'directives/checkbox.html';
restrict: 'E',
transclude: true
}
}]);
directives/checkbox.html
<label class="styling" ng-transclude>
... some other html
</label>
We extensively use modals throughout our application and are in the process of converting everything to bootstrap's angular directive. We've created a controller that handles a particular type of modal that appears sporadically throughout out application:
angular.module('namespace.controllers').controller('LegalModalController',
['$scope', '$modal',
function($scope, $modal) {
$scope.showLegalModal = function(title, legalTextLocation) {
$modal.open({
templateUrl: 'modals/legal.html',
controller: 'sc.LegalModalInstanceController',
resolve: {
modalTitle: function() {
return title;
},
template: function() {
return eulaTextLocation;
}
}
});
};
}]);
Coming back to the directive piece, there is a case where we need to add a link within the checkbox directive that hooks into the legal controller to pop open a modal window. This is what's being done thus far:
<some-checkbox>Click <a href ng-controller="LegalModalController" ng-click="showLegalModal()">here</a> to...</some-checkbox>
The problem that we're encountering is that we have been thoroughly unable to inject $modal into the controller without getting the following error:
Unknown provider: $modalProvider <- $modal
I've looked everywhere, but I haven't found any others who are in this scenario. Does anyone know what could be the potential root of this problem? This linking works in every case where we are not using a directive.
This is the main.js file that starts up the app:
angular.module('namespace.modules.main', ['namespace.core', 'ui.select2', 'ngSanitize', 'ui.sortable', 'infinite-scroll', 'ui.bootstrap']).
config(['$routeProvider', '$locationProvider', '$httpProvider', '$compileProvider',
function($routeProvider, $locationProvider, $httpProvider, $compileProvider) {
routeProvider = $routeProvider;
$locationProvider.html5Mode(true).hashPrefix('!');
$httpProvider.defaults.headers.patch = {};
$httpProvider.defaults.headers.patch['Content-Type'] = 'application/json; charset="UTF-8"';
// Allow telephone hyperlinks
$compileProvider.urlSanitizationWhitelist(/^\s*(https?|mailto|tel):/);
}]).run(
['$rootScope', '$location', '$timeout', '$window', '$route'
function($rootScope, $location, $timeout, $window, $route) {
// set up $rootScope and route provider here
});
I was able to figure it out. The specific page within our application that this was failing on was its own module, and thus didn't have the correct bootstrap ui dependencies. Oops >.< .

Categories

Resources