cannot run log method in config method for angular - javascript

I'm trying to intercept specific calls and show an alert to the user. There's already existing code on our project that looks like:
myModule.config([
'$routeProvider', '$locationProvider', "$httpProvider",
($routeProvider: ng.route.IRouteProvider, $locationProvider: ng.ILocationProvider, $httpProvider: ng.IHttpProvider) => {
console.log("in my module");
if (history.pushState) {
$locationProvider.html5Mode(true);
$routeProvider.when('/projects', {
template: Templates.projects,
controller: projectsListControllerName
});
} else {
$routeProvider.when('/', {
template: Templates.projects,
controller: projectsListControllerName
});
}
}
]);
Is there something wrong with console.log("in my module"); in the config method of myModule? My routes still work going to /projects and /, but I never see "in my module" in the console.

Is there something wrong with console.log("in my module"); in the config method of myModule?
Nope. It's okay
My routes still work going to /projects and /, but I never see "in my module" in the console.
/ is guaranteed to work as long as you have a server route returning /. Most likely the same is applying for /projects i.e. the server is returning the page but client side angular isn't picking up the details for /projects
What is broken?
Most likely you don't have an ng-app pointing to the module or if you are using requirejs you are missing a angular.bootstrap call after you load this file.

Related

$routeParams not populating

Some I'm new to routing and single page web apps, but I've been trying to learn Angular correctly. There's some trouble I'm experiencing with it however and a few weird questions. I followed a guide on structuring your directory and mine looks something like this:
app/
components/
profile/
profile.html
ProfileModel.js
ProfileController.js
ProfileFactory.js
app.module.js
app.routes.js
My main module is located in app.module.js and is dependency injected with ngRoute and profile.app (the module for profile view from ProfileModel.js). It is declared like this:
angular
.module('app', ['ngRoute', 'profile.app'])
.controller('MainController', MainController);
function MainController() {
this.message = 'This is the home page';
}
Then in my app.routes.js file, I have declared all the routes the applications needs (so far only one, which is profile):
angular
.module('app')
.config(routeConfig);
routeConfig.$inject = ['$locationProvider', '$routeProvider'];
function routeConfig ($locationProvider, $routeProvider) {
$routeProvider
.when('/user/:user_id', {
templateUrl: '/app/components/profile/profile.html',
controller: 'ProfileController',
controllerAs: 'profile'
}
)
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
This is my ProfileController.js:
angular
.module('app.profile')
.controller('ProfileController', ProfileController);
ProfileController.$inject = ['ProfileFactory', '$routeParams'];
function ProfileController(ProfileFactory, $routeParams) {
var vm = this;
vm.user_id = $routeParams.user;
console.log($routeParams.user_id);
vm = ProfileFactory.userProfile(vm.user_id); //Gets the profile of the user and sets to to vm
}
So I have two main questions. $routeParams.user_id is logged as nothing despite I have defined the route in app.routes.js. This is weird because I have an ng-view directive in my index.html (the HTML file that includes every single .js file). Which means that I should have immediate access to the routing parameters once the controller and its dependencies are instantiated. However, when I go to http://example.com/user/1, I get nothing logged (undefined).
My second question is I included ngRoute as a dependency in profile.app and my main module (in which profile.app is a dependency). However, I later removed ngRoute from profile.app as a dependency, yet I left the injection of $routeParams inside my ProfileController and AngularJS didn't complain at all. This seems weird because the dependency is no longer explicitly present inside profile.app. So how come I can still seemingly inject $routeParams despite not having ngRoute in my profile.app module? Is it because it is getting ngRoute from the main module?
I believe the problem is that you are setting controllerAs to 'profile' but then in the controller you write var vm = this;
These two need to be the same so you could write controllerAs: 'vm', or var profile = this;

Angular controller is not instantiated after minification

My original source code looks like this:
(function(angular) {
'use strict';
/* #ngInject */
function config($stateProvider) {
$stateProvider
.state('bar.foo', {
url: '/foo',
templateUrl: 'foo-view.html',
controller: 'FooController',
controllerAs: 'vm'
});
}
/* #ngInject */
function FooController() {
window.alert('foo');
}
angular
.module('my.foo', [])
.config(config)
.controller('FooController', FooController);
}(angular));
It works fine this way.
Then I minify it using ngAnnotate and UglifyJS, and get this code (formatted to easier reading):
function (a) {
'use strict';
function b(a) {
a.state('bar.foo', {
url: '/foo',
templateUrl: 'foo-view.html',
controller: 'FooController',
controllerAs: 'vm'
})
}
function c() {
window.alert('foo')
}
b.$inject = ['$stateProvider'],
a.module('my.foo', [])
.config(b)
.controller('FooController', c)
}(angular),
And, it does not work. When I go to the state bar.foo the controller do not get called. Others controllers and router states works fine. This one seems to get muted, the code inside the controller function is not called.
The console do not show any errors.
I do not know what to do or where to look at.
The entire JavaScript is bigger and is a concatenation of several small files. The single minified JS file has controllers before and after this one that works fine.
Debugging the minified file shows that the JavaScript is issuing the module definition calls to AngularJS, so the module, config and controller methods of Angular are called.
What should I search or check in the code? Am I missing something?
My problem was that I'm also compiling Jade templates into HTML. And my build settings for production environment is a little different than for development. Jade were outputting <div ui-view="ui-view"> instead of an empty attribute, preventing the ui-router to load the template into the parent view, causing the controller to not being instantiated.
The minification of the JavaScript was not the problem. Sorry.
These questions helped me out:
ui-router nested route controller isn't being called
Grunt jade compiler filling out empty attributes

Angular $routeProvider override-able fallback routes

I'm creating my first sizable angular project, so I've opted to break out my angular application code into directories like so:
app/
calendar/
calendar.js
contacts/
contacts.js
companies/
companies.js
...
app.js
Each of these directories will include a handful of files for views (.html), directives, services, etc.
In my app.js file, I want to setup default routes that will be used maybe 80% of the time, like this:
$routeProvider
.when('/:page', {
templateUrl: function($routeParams) {
return 'app/' + $routeParams.page + '/index.html';
},
controller: 'PageController'
})
However, I want the ability to "override" that route from within my modules so I can do things like swap out the controller, do dependency injection stuff, and so on. I would like that sort of logic contained within the module itself to keep things...well...modular, so I would rather not define each module's routing logic within app.js. So for example, in my app/calendar/calendar.js file I want to say:
$routeProvider
.when('/calendar', {
templateUrl: 'app/calendar/index.html',
controller: 'CalendarIndexController',
resolve: { ... }
})
The problem is that the definition in app.js is matched against the location first, so this calendar route is never used.
To achieve this, right now I'm just including an extra file after all of my module javascript files that sets up my fallback routes last, but this seems a little clunky. Is there anyway to define the routes within app.js so that they are override-able?
You might be able to adapt this technique for dynamically loading controllers described by Dan Wahlin here http://weblogs.asp.net/dwahlin/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs combined with your default routes where the parameter controls which view to load. You could pass the same page parameter to the resolve function to control which combination of view and controller to serve up?

Routing error in AngularJS

What's wrong with this AngularJS configuration code?
(function () {
var ip = 'x.x.x.x';
var app = angular.module('cmal', ['controllers', 'directives', 'services', 'ngRoute'])
.constant("baseUrl", "http://" + ip + ":303/angular")
.config( function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', { templateUrl: "index.html"});
$routeProvider.when('/users', { templateUrl: "users.html"});
$routeProvider.otherwise({template: "Sorry, the page you are trying to reach doesn't exist."});
});
})();
EDIT: it's not the slash error. This still doesn't work for me and all i get in the console is "Uncaught object"
EDIT 2: Well i didn't realize you needed to import another js script for routing. But so now that I have done that, I get no error, but none of the routes work.
You are probably not including the separate angular-route script.
Take a look at this answer for more details.
This isn't really an answer, but an alternative solution...I used a separate routing framework.
UI-Router (a link to the egghead tutorial)

Angular Uncaught Object

I'm new to Angular so i'm still getting my head around how it works. I've stumbled into a problem however (quite early on...) and the below code is giving me "Uncaught Object" in the console and breaks Angular. The .config section is the culprit, if I remove it, the page loads fine. I'm not entirely sure how the error is being caused because to me, everything looks fine?
var app = angular.module('app', ['ngRoute'])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: '/app/views/admin.html',
controller: 'DashboardController'
})
.otherwise('/', {
redirectTo: '/'
})
$locationProvider.html5mode(true);
}])
.controller('DashboardController', ['$scope', function ($scope, Security) {
$scope.security = Security;
}])
I had the same error; if you activate Chrome to pause on exceptions, you'll be able to have more detailed error information
.otherwise takes only one parameter - an object which contains information on what needs to be done for routes that are not defined.
In your case, you seem to be passing a route to it in addition to an object.
Replace:
.otherwise('/', {
redirectTo: '/'
})
with
.otherwise({
redirectTo: '/dashboard'
});
Note that you need to redirect to a path that exists. '/' is a path that does not exist. '/dashboard' is a path that does, hence you redirect to it. Or, define a handler for '/' path
I'm posting my own solution, as several factors seem to be behind this issue and nobody has talked about this so far.
That is, try to write your code outside of $.ready();
<script>
$(function(){
// This leaves "Uncaught object" error in Chrome!
// var app = angular.module('testApp', ['ngRoute']);
});
// So get it out of $.ready()!!
var app = angular.module('testApp', ['ngRoute']);
</script>
In this instance it looks like the error has been caused by this:
$locationProvider.html5mode(true); <-- mode should be capital 'M'.
Be sure your angular.js is loaded before angular-route.js in your HTML file.
like:
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-route.js"></script>
I just ran into this, in my case it was due to using UI-Router and having a duplicated state name.

Categories

Resources