How to debug this angular js code? - javascript

When errors happen inside of angular, debugging seems impossible for me. I have this code:
<script>
var my_app = angular.module("campaign_listing", ['$http']);
var controllers = {};
controllers.campaign_list_controller = function($http){
var filters = {};
var campaigns = {};
this.update_fields = function(){
console.log("update!");
}
}
my_app.controller(controllers);
</script>
And it throws this error:
angular.js:38Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.6/$injector/modulerr?p0=campaign_listing&p1…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.4.6%2Fangular.min.js%3A19%3A463)
And without the minified version:
Uncaught Error: [$injector:modulerr] Failed to instantiate module campaign_listing due to:
Error: [$injector:modulerr] Failed to instantiate module $http due to:
Error: [$injector:nomod] Module '$http' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.6/$injector/nomod?p0=%24http
I'm not using routing, so that link actually confuses me.
Can someone tell me what the problem is and how to debbug this in the future?

You could create a breakpoint in the line of my_app.controller() and step into the Angular code (good luck, that's hard for beginners).
Only from reading your code, I suggest to try this:
<script>
var my_app = angular.module("campaign_listing", []);
var campaign_list_controller = function($http){
var filters = {};
var campaigns = {};
this.update_fields = function(){
console.log("update!");
}
}
my_app.controller('campaign_list_controller', campaign_list_controller);
</script>
I suppose you might get even more problems later, because this all doesn't look much like typical Angular code. My advise: try to exercise with the Tutorial first.

The previous answer is correct but this is can also happen when you do NOT include a Controller file. Example below shows at line 60 I had commented out the controller file but at line 13 I was actually referencing a AppCtrl. If I uncomment the line 60 the error goes away.
Here is what you would get on console:

Related

How to inject ngRoute into Jasmine / Karma AngularJS unit test?

I'm trying to get a basic unit test example working. It all works fine with this app.js
var whapp = angular.module('whapp', [])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}]);
and this spec.js
describe('Filters', function(){ //describe your object type
beforeEach(module('whapp')); //load module
describe('reverse',function(){ //describe your app name
var reverse, rootScope;
beforeEach(inject(function($filter){ //initialize your filter
reverse = $filter('reverse',{});
}));
it('Should reverse a string', function(){ //write tests
expect(reverse('rahil')).toBe('lihar'); //pass
});
});
});
with this karma files config
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-mocks/angular-route/angular-route.js',
'node_modules/angular-mocks/angular-ui-router/release/angular-ui-router.js',
'app/js/*.js',
'tests/*.js'
]
The problem occurs when I try to inject ngRoute into my module in app.js like so
var whapp = angular.module('whapp', ['ngRoute'])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}]);
In which case I get the following error in karma [UPDATE: this error occurs even if I don't load the angular-mock.js library into karma as shown above]
TypeError: undefined is not a constructor (evaluating 'reverse('rahil')') in tests/spec.js (line 9)
So... how do I inject ngRoute into spec.js correctly? I've tried a variety of things, none of which worked.
Apparently, you get this error because PhantomJS fails to instantiate your main Angular module whapp. One possible reason is, that the file node_modules/angular-mocks/angular-route/angular-route.js is missing.
Obviously, you are using npm to manage your dependencies. So try to replace your current file with:
node_modules/angular-route/angular-route.js
The same for the ui-route module:
node_modules/angular-ui-router/release/angular-ui-router.js
I hope this will help you.

Angular + Karma/Jasmine: Error: [$injector:nomod] Module 'md.data.table' is not available

I am using Karma and Jasmine to test my Angular application.
I have this spec below:
"use strict";
describe("SuperHeroService", function () {
var SuperHeroService, $httpBackend;
beforeEach(module('beAwesome'));
beforeEach(module("beASuperHero"));
beforeEach(function () {
inject(function (_SuperHeroService_, _$httpBackend_) {
SuperHeroService = _SuperHeroService_;
$httpBackend = _$httpBackend_;
});
});
it("should initialize correctly", function () {
expect(SuperHeroService).toBeDefined();
});
The md.data.table dependency is included in the beAwesome module, which I'm including in my beforeEach block. beAwesome module is called in beASuperHero as well.
I've also referenced the SuperHeroService, beAwesome and beASuperHero in my karma.conf file.
However, I cannot figure out why the md-data-table (Github project: https://github.com/iamisti/md-data-table) won't be instantiated and keeps breaking, no matter what I do:
Error: [$injector:modulerr] Failed to instantiate module beASuperHero due to:
Error: [$injector:modulerr] Failed to instantiate module md.data.table due to:
Error: [$injector:nomod] Module 'md.data.table' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
I'm sure I'm just missing some configuration or a line of code but after hours of searching, I haven't found anything that's been helpful! Any hints to get unstuck is much appreciated.
Thanks

Error while requiring external library with browserify (this = undefined)

I'm trying to require the library Chart.js with Browserify (tbh it's development environment with gulp, browserify and some other stuff that I barely know how it works togheter):
'use strict';
var angular = require('angular');
require('angular-ui-router');
require('./templates');
require('./controllers/_index');
require('./services/_index');
require('./directives/_index');
window.gauge = require('./vendors/gauge');
//this is what i'm trying to require
window.chartjs = require('./vendors/chart');
angular.element(document).ready(function() {
var requires = [
'ui.router',
'templates',
'app.controllers',
'app.services',
'app.directives'
];
window.app = angular.module('app', requires);
angular.module('app').constant('AppSettings', require('./constants'));
angular.module('app').config(require('./routes'));
angular.module('app').config(require('./PostFix'));
angular.module('app').run(require('./on_run'));
angular.bootstrap(document, ['app']);
});
Tbh it did work well with window.gauge = require('./vendors/gauge'); but when I require vendors/chart.js it throws this error:
undefined // chart.js:4
Uncaught TypeError: Cannot read property 'Chart' of undefined // chart.js:4
And here is those lines in the chart.js file:
(function(){
"use strict";
console.log(this); <------ outputs the "undefined"
var root = this,
previous = root.Chart; <----- fails, as "root" doesn't exist
It's weird, because when I add chart.js using <script></script> that console.log(this) outputs the window object/scope, but when executed from browserify, it's undefined, that's why the chart.js fails.
I'm a total newb with browserify/node/gulp, but I tried different stuff such as:
Browserify-shim -> same error
Requiring the script in different ways, like trying to require it inside an object { }, trying to do a var whatever = new require('./vendors/chart') but failed miserably like a beheaded chicken trying to go to the bathroom.
I'm guessing that somehow I have to attach that script to an object or something so this would not be undefined when executed, but I'm failing to find the way.
I already solved it. The problem was a browserify transform called Babelify. I still don't know why Babel was doing that, but I didn't need it anyway so I just disabled it and that was it. Just posting it here in case it happens to someone else.

custom blur not working correctly [AngularJS]

I am trying to create notifications something like this:
http://plnkr.co/edit/GbFioFDNb2OC4ZjARQTp?p=preview
But I am unsuccesful to integrade it in my script, because when I click outside notification box nothing happend.
Here is my script:
'use strict';
var app = angular.module('notifications',['ngRoute'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
})
.controller('NotificationController', function($scope, $http) {
$http.get("/api/notification")
.success(function (response) {
$scope.notys = response;
});
$scope.notifications = {
visible: false
};
$scope.showNotifications = function(flag) {
$scope.notifications.visible = flag;
};
})
.directive('customBlur', function(){
return {
restrict: 'A',
scope: {
'customBlur': '='
},
link: function(scope, element, attr) {
element.on('click', function(event){
var targetAttr = angular.element(event.target).attr('custom-blur');
console.log(targetAttr);
if (typeof targetAttr !== 'undefined') {
scope.$apply(function(){
scope.customBlur = false;
});
}
});
}
};
});
Problem is when I click outside notifcation box it not return anything but shuld return notification.visible if I click into notification box it return undefined as expected.
that is result for: console.log(targetAttr);
I ran your code in plunkr and tried to fix the error.
All I found is that your module name and controller name were not same.
Uncaught Error: [$injector:modulerr] Failed to instantiate module demo due to:
Error: [$injector:nomod] Module 'demo' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.2/$injector/nomod?p0=demo
This error says that angular is not able to find the module 'demo'. So I made changes to HTML here. This line:
<html ng-app="notifications">
After that I got this error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module notifications due to:
Error: [$injector:modulerr] Failed to instantiate module ngRoute due to:
Error: [$injector:nomod] Module 'ngRoute' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
This says that ngRoute which you are using here angular.module('notifications',['ngRoute'], function($interpolateProvider) { is not available. So I just removed it. (just to fix the error.).So I did changes to js. This line:
angular.module('notifications',[], function($interpolateProvider) {
ok After that I got this error:
Error: [ng:areq] Argument 'Ctrl' is not a function, got undefined
http://errors.angularjs.org/1.4.2/ng/areq?p0=Ctrl&p1=not%20a%20function%2C%20got%20undefined
Which says that Ctrl is not defined properly.So I made changes to HTML again.This line
<body ng-controller="NotificationController">
ok. After fixing all this I found no more error. and your plunker started working again.
you can see the plunker here : plunker
Hope this helps you. Thank you.

Error: [$injector:modulerr]

I am a newbie. Just learning/trying to integrate Angular with my webapp (Java + jQuery+ requireJS). I am not using any router and below is my script. From other stackoverflow I learned that this error is due to missing inclusion of ngRoute module. Since version 1.1.6 it's a separate part. But in my below code I am not at all using any ngRouter. When I am not referencing it why am I getting this error ?
Error: [$injector:modulerr] Failed to instantiate module counter due to: [$injector:nomod] Module 'counter' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. http://errors.angularjs.org/1.2.11/$injector/nomod?p0=counter
Template:
<ul ng-app="counter" ng-controller="counterController">
<li>
<span class="ui-button-text" ng-bind="critical"></span>
</li>
<li>
<span class="ui-button-text" ng-bind="error"></span>
</li>
<li>
<span class="ui-button-text" ng-bind="warn"></span>
</li>
<li>
<span class="ui-button-text" ng-bind="note"></span>
</li>
</ul>
JS
requirejs.config({
paths : { angular: "/js/lib/angular/angular.min" },
shim : { "angular": { deps: [ "jquery"], exports: "angular" } }
});
require(["angular", "jquery"],function() {
var module = angular.module('counter', []);
module.controller('CounterController', function ($scope, $http, $timeout) {
$scope.critical = 0;
$scope.error = 0;
$scope.warn = 0;
$scope.note = 0;
function setData(d){
$scope.critical = d.critical;
$scope.error = d.error;
$scope.warn = d.warn;
$scope.note = d.note;
}
var getCounters = function() {
var config = {headers: {
'X-MY-Request': (new Date()).getMilliseconds()
}
};
$http.get('xxxxxxx', config)
.success(function(data, status, headers, config) {
setData(data);
$timeout(getCounters, 60000);
}).error(function(data, status, headers, config) {
// Handle the error
});
}
$timeout(getCounters, 500);
});
In your template your controller name has a lowercase beginning letter counterController. Your js has it with an uppercase CounterController. Could this be the issue?
Any injected module that isn't found will throw an error. Not just ngRoute.
Edit:
I just threw a quick plunker together and without the 'require' stuff all your code is correct. So no you aren't missing anything in your angular code. All modules are working.
So the problem must be with your 'require' setup. I have literally never used it so couldn't really assist you. Look here for more Angular + Requirejs - Loading in the wrong order.
For now, if I were you, I would learn one technology at a time. Just load your angular and jquery resources and then learn how to use them. Then when you are getting a little more comfortable add 'require'.
Had the same problem, to get more info about the error call the bootstrap function with {debugInfoEnabled: true} like so:
angular.bootstrap(document.getElementById('app-root'), ['MyApp'], {debugInfoEnabled: true});
This will print out to the console what's the underlining module that fails to instantiate.
If the $injector:modulerr shows up in your test framework you may have to include the module in your test framework as well. For me it was karma and phantomjs needing an include in:
test/karma.config.js
I encountered this error with my root app module not loading.
Eventually I reordered my dependancy list and the error whent away.
hope that helps someone. Cost me an hour!

Categories