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

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

Related

How to separate a component's controller function into a different file?

I have been searching and searching, and maybe I have been using the wrong terms on my search, but I couldn't find exactly what I was looking for. I am using Angular 1.5 with components.
Say I have a component A:
var module = angular.module('myApp');
module.component('A', {
templateUrl: 'template.html',
controller: function(){}
});
Now this is very simple. I also know that I can do the following, as long as 'myControllerFunction' is in the same file.
var module = angular.module('myApp');
module.component('A', {
templateUrl: 'template.html',
controller: myControllerFunction
});
function myControllerFunction(){}
Now what do I do if I want to have a file only for 'myControllerFunction'? How do I access that function inside that file from within my component?
I know that using Node.js is easy to use exports and require(), but I am not quite familiar what to do using AngularJS.
Any help would be very much appreciated! Thank you!
you can refer the controller from your module like below :
module.component('A', {
templateUrl: 'template.html',
controller: 'YourController'
});
Then in the another file you can define controller with the method.
function() {
'use strict';
angular.module('app').controller('YourController',
YourController);
YourController.$inject = [ '$scope', '$http', '$window',
'$rootScope' ];
function YourController($scope, $http, $window, $rootScope) {
function yourcontrollerfunction() {
}
yourcontrollerfunction();
}
})();
yourcontrollerfunction function will automatically called when controller is loaded. Controller will be loaded when your module is loaded.

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.

Why angular returns with referenceError: ngResource is not defined?

I've done quick client-side routing with angular 1.4.4. In every tutorial I saw approach where you assign module to variable (usually: app) and perform different tasks on it, like below:
var app = angular.module('skeleton', [ngResource, ngRoute]);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/', {
templateUrl: '/partials/main',
controller: 'MainController'
});
});
app.controller('MainController', function ($scope) {
$scope.test = 'Hi Angular';
});
In tutorial which I'm doing now I see completely different approach:
angular.module('skeleton', ['ngResource', 'ngRoute']);
angular.module('skeleton').config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});
});
angular.module('skeleton').controller('mainCtrl', function($scope){
$scope.test = "Hello Angular";
});
I assumed it's just preference, so i went with 'app' version as I find it more readable.
Unfortunately it causes angular to throw
ReferenceError: ngResource is not defined
Anyone know what is cause of this behaviour?
Which approach do you prefer?
You need to to inject dependency properly, pass ngResource and ngRoute within quotes, otherwise they are treated as variable hence you must be getting the error.
var app = angular.module('skeleton', ['ngResource', 'ngRoute']);
Firstly , The issue is not with assigning the module declaration to a variable 'app' and then using it. Both approaches work but it is better to declare without assigning it to a variable which avoids variable collisions which could lead to module overriding.
The issue in your code is the syntax. Please correct it as shown below :
var app = angular.module('skeleton', ['ngResource', 'ngRoute']);
dependency Annotation can also be done by assigning the array of dependencies to the '$inject' property or directly as the function properties .
Please refer to this angular guide for reference :
https://docs.angularjs.org/guide/di

AngularJS - How to refer to a submodule controller from ui-router?

I'm struggling a bit with having submodules in an Angular 1.3.9 app. I've got a (non-working, sorry) preview at http://plnkr.co/edit/XBfTPAGRRe0CWJgjGJzc?p=preview and I think it's freaking out, in part, because I'm using Restangular.
I have the following:
angular
.module('estimate', ['ui.router', 'restangular', 'estimate.project'])
;
angular
.module('estimate.project', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider'
, function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('project', {
url: "/project/{id:int}",
abstract: true,
templateUrl: '/app/templates/project.html',
controller: "ProjectController as project",
resolve: { // stuff }
})
.state('project.overview', {
url: "",
templateUrl: "/app/templates/overview.html"
})
// ...
;
}])
.controller('ProjectController', ['$scope', 'ProjectService', 'myProject'
, function($scope, ProjectService, myProject) {
console.log('i made it!');
}]);
And in my template, which is served from the estimate module, I have:
<li><a ui-sref="project.overview({ id: 1 })">One</a></li>
The URL resolves correctly on the page, but clicking on it does nothing. It doesn't even throw any console errors - it just sits there. My gut tells me it has to do with how I'm referring to the controllers and/or the routes, and if they need to be prefixed or modified to work with a submodule. Any ideas on how to get it to load properly?
If this post is too scatterbrained, let me know and I'll try to clean it up.
I updated your plunker here and would say, that the most important change is - referencing sub-module in the main module:
Instead of this:
angular
.module('estimate', ['ui.router', 'restangular'])
...
angular
.module('estimate.project', ['ui.router'])
...
We have to use this, i.e. reference sub module in a parent module
angular
.module('estimate', ['ui.router', 'restangular', 'estimate.project'])
...
angular
.module('estimate.project', ['ui.router'])
...
With some few other small adjustments, that should be the way. Check it working here

How do you access route parameters in an AngularJs Controller

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.

Categories

Resources