Module Exceptions in Angularjs and $exceptionHandler - javascript

In the documentation of Angular 1 for $exceptionHandler it says:
Any uncaught exception in angular expressions is delegated to this service.
https://code.angularjs.org/1.3.20/docs/api/ng/service/$exceptionHandler
Yet when I get a module initialisation error (Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: ...) it does not seem to get logged via the $exceptionHandler.
I want to be able to log these Errors to Sentry via Raven and am having trouble finding a solution to this.
This is an example of what i am trying to achieve:
// Main App module
angular.module('app', ['app.welcome', 'app.contact'])
.factory('$exceptionHandler', [function() {
return function myExceptionHandler(exception, cause) {
// why does the module initialisation error not get caught here..?
console.log("[ERROR] ", exception.message);
};
}]);
// a module I forgot to load..
// app.module('app.contact', []);
// another sub module
angular.
module('app.welcome', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.test = function() {
$window.alert('test');
};
}]);
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="test()">Test</button>
</body>
</html>

Here is a snippet which raise an error because $q is not injected, do whatever you want in custom exception handler.
angular.module('app', []);
angular.
module('app')
.controller('ExampleController', ['$scope', function($scope) {
$scope.test = function() {
$q.when("foo");
};
}])
.factory('$exceptionHandler', [function() {
return function myExceptionHandler(exception, cause) {
console.log("[ERROR] ", exception.message);
};
}]);
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="test()">Raise Error</button>
</body>
</html>

Related

App is breaking due to factory in angularjs. Why?

I have no idea why this code is breaking...
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"> </script>
<script>
var app = angular.module('test', []);
app.service('mySerivce', function($scope) {
return 0;
});
app.controller('myController', function($scope, myService) {
});
</script>
</head>
<body ng-app='test'>
<div ng-controller="myController">
</div>
</body>
</html>
I am getting the error message:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.6/$injector/unpr?p0=myServiceProvider%20%3C-%20myService%20%3C-%20myController
$scope is not available to factories or services. Also I misspelled myService.
Add controller dependency in string array format, like below:
.controller('MyController', ['myService', function (myService) {
}]);
You can refer this in Error: [$injector:unpr]

Angularjs service for directive is unknown if in same file

Error only if minimized and loaded in same file.
If app.ts is loaded before Service or Directive it works.
(No problems with controllers)
How can i make it work?
Console Error:
site.js:119 Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=eProvider%20%3C-%20e%20%3C-%20routeNavigation%20%3C-%20navigationDirective
at Error (native)
at http://localhost:50308/js/site.js:11:416
at http://localhost:50308/js/site.js:48:7
at Object.d [as get] (http://localhost:50308/js/site.js:45:270)
at http://localhost:50308/js/site.js:48:69
at d (http://localhost:50308/js/site.js:45:270)
at e (http://localhost:50308/js/site.js:46:1)
at Object.invoke (http://localhost:50308/js/site.js:46:86)
at Object.$get (http://localhost:50308/js/site.js:43:460)
at Object.invoke (http://localhost:50308/js/site.js:46:295)(anonymous function) # site.js:119
AngularJs Error Message:
Unknown provider: eProvider <- e <- routeNavigation <- navigationDirective
app.ts
enter code here
"use strict";
var app = angular.module('HouseConcertApp', ['ngCookies', 'pascalprecht.translate', 'ngRoute', 'houseconcertControllers', 'houseconcertServices', 'houseconcertDirectives']);
app.config([
'$translateProvider', '$routeProvider', function($translateProvider, $routeProvider) { ....
services.ts
var houseconcertServices = angular.module('houseconcertServices', []);
houseconcertServices.factory('routeNavigation', function ($route, $location) {
var routes = [];
angular.forEach($route.routes, function (route, path) {
if (route.name) {
routes.push({
path: path,
name: route.name
});
}
});
return {
routes: routes,
activeRoute: function (route) {
return route.path === $location.path();
}
};
});
directives.ts
var houseconcertDirectives = angular.module("houseconcertDirectives", []);
houseconcertDirectives.directive('navigation', ['routeNavigation', routeNavigation => ({
restrict: "E",
templateUrl: "navigation-directive-tpl.html",
controller($scope) {
$scope.routes = routeNavigation.routes;
$scope.activeRoute = routeNavigation.activeRoute;
}
})]);
index.html
<!doctype html>
<html ng-app="HouseConcertApp">
<head>
<base href="/index.html">
<title>House Concert</title>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/Main.css"/>
<script src="js/site.js" onload="Hc.Common.initialize()"></script>
</head>
<body>
<navigation></navigation>
<div ng-controller="HouseConcertCtrl">
<div ng-view></div>
</div>
</div>
</body>
</html>
it works if html head script includes like this:
but not if all in this order minimized in site.js (with gulp)
<script src="pathToFolder/app.ts"></script>
<script src="pathToFolder/services.ts"></script>
<script src="pathToFolder/controllers.ts"></script>
<script src="pathToFolder/directives.ts"></script>
To get files minified without error you should make sure to follow Dependency Injection pattern consistently. Only routeNavigation factory code is missing DI Inline Array annotation in your code.
Change below
houseconcertServices.factory('routeNavigation', function ($route, $location) {
to
houseconcertServices.factory('routeNavigation',['$route', '$location',
function ($route, $location) {
//service code will be as is.
}]);
Doc link for minification related warning

Getting error while using ngRoute in Angular.js

I am getting the following error while using Angular.js in my app.
Error:
angular.js:38Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.6/$injector/modulerr?p0=app&p1=Error%3A%20%…oudflare.com%2Fajax%2Flibs%2Fangular.js%2F1.4.6%2Fangular.min.js%3A41%3A35)
I am providing my code below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="app">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DEMO</title>
<link href="bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-route.js"></script>
<script src="angularuirouter.js" type="text/javascript"></script>
</head>
<body>
I want to go for a trip
<div ng-view></div>
<script src="script.js"></script>
</body>
</html>
script.js:
"use strict";
var app = angular.module( "app",[],function( $routeProvider ) {
$routeProvider.when( "/visitplace", {
templateUrl: "placetovisit.html",
controller: "TourCoordinatorCtrl",
resolve: {
"accommodation": function( $q, $timeout ) {
var myFriend = $q.defer();
$timeout(function(){
myFriend.resolve({
hotelName: function( ) {
return "My Friend's friend's hotel";
},
roomNo: function( ) {
return "404";
}
});
},5000);
return myFriend.promise;
}
}
});
} );
app.controller( "TourCoordinatorCtrl", function( $scope, accommodation ) {
$scope.name = "Shidhin";
$scope.place = "Switzerland";
$scope.hotel = accommodation.hotelName( );
$scope.roomno = accommodation.roomNo( );
} );
How can I resolve this error?
You haven't injected the ngRoute module into your app. That is why you are getting an injector error.
You must define your app like this (for example):
var app = angular.module( "app", ['ngRoute']);
Then configure the route provider.
Missing ngRoute injection on your main module.
angular.module('app', ['ngRoute'])
angular.module("app",[]).config(["$stateProvider","$urlRouterProvider",
function($stateProvider,$urlRouterProvider)
{
url routeprovider
}])
The previous answers are correct but this 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 see on the console:

Defining angular modules in different files

I have 3 js files in my application
(mainApp.js, template.js, app.js)
index.html
<html lang="en" ng-app="myapp">
mainApp.js
var app = angular.module('myapp',
['myapp.templateApp', 'myapp.demoApp']);
template.js
angular.module('myapp.templateApp', ['slick', 'localization'])
.controller('CountryLaunguageSelection', [
'$scope', '$rootScope','$http',
function($scope, $rootScope,$http) {
}
]);
app.js
var app = angular.module('myapp.demoApp', [
'ui.router',
'ui.grid',
'ngTouch',
'ui.grid.selection',
'ui.bootstrap',
'ngTable'
]);
app.config(function($stateProvider, $urlRouterProvider) {
});
I need the 3 modules to be in 3 different files.Could anybody tell me what is wrong with the above code.
I am getting the below error
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.28/$injector/modulerr?p0=app&p1=Error%3A%20…0%2FdemoApp%2Ftemplate%2Fthird-party%2Fangular%2Fangular.min.js%3A18%3A387)
Just created such a localhost - it works. Try to compare your index.html and dependencies.
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myapp">
<head lang="en">
<meta charset="UTF-8">
<script src="angular.min.js"></script>
<script src="mainApp.js"></script>
<script src="app.js"></script>
<script src="template.js"></script>
</head>
<body>
<div ng-controller="CountryLaunguageSelection">
{{data.myData}}
</div>
</body>
</html>
mainApp.js
var app = angular.module('myapp', ['myapp.templateApp', 'myapp.demoApp']);
app.js
var app = angular.module('myapp.demoApp', []);
app.config(function() {
});
template.js
angular.module('myapp.templateApp', [])
.controller('CountryLaunguageSelection', [
'$scope', '$rootScope','$http',
function($scope, $rootScope, $http) {
$scope.data = {
myData: "Hello"
};
}
]);

End-to-End Testing AngularJS app with Jasmine

I have an AngularJS app. I would like to implement some end-to-end testing that I can run on-demand. In an effort to do this, I've built a basic test screen with the following:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Results</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-mocks.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" />
<!-- Load the Test Files-->
<script type="text/javascript" src="e2e/tests.e2e.js"></script>
</head>
<body>
run tests
</body>
</html>
My tests.e2e.js file looks like the following:
'use strict';
describe('MyApp', function() {
browser.get('http://localhost:11000/index.html');
describe('Welcome Screen', function () {
});
});
When click "run tests" in my test runner, I get an error that says:
MyApp encountered a declaration exception
ReferenceError: browser is not defined
My question is, what am I doing wrong? The examples I've seen use browser to basically start the app. However, I can't seem to figure out how to do end-to-end tests on-demand.
Thank you for any help you can provide.
(function (module) {
var myController = function ($scope, $http) {
$http.get("/api/myData")
.then(function (result) {
$scope.data= result.data;
});
};
module.controller("MyController",
["$scope", "$http", myController]);
}(angular.module("myApp")));
describe("myApp", function () {
beforeEach(module('myApp'));
describe("MyController", function () {
var scope, httpBackend;
beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
httpBackend.when("GET", "/api/myData").respond([{}, {}, {}]);
$controller('MyController', {
$scope: scope,
$http: $http
});
}));
it("should have 3 row", function () {
httpBackend.flush();
expect(scope.data.length).toBe(3);
});
});
});

Categories