Angularjs service for directive is unknown if in same file - javascript

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

Related

Uncaught Error: [$injector:nomod] for Component

I've been working on a project for a class and I am getting The [$injector:nomod] error even after declaring a module.js file. I'm still new to angular, I still went and checked all the other questions that had the same problem as me but non of them answered/worked for my problem. Here is my code, please help.
Error:
Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.6.5/$injector/nomod?p0=MenuAppX
at angular.min.js:7
at angular.min.js:26
at b (angular.min.js:25)
at Object.module (angular.min.js:26)
at categories.component.js:4
at categories.component.js:12
Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.6.5/$injector/nomod?p0=MenuAppX
at angular.min.js:7
at angular.min.js:26
at b (angular.min.js:25)
at Object.module (angular.min.js:26)
at items.component.js:4
at items.component.js:12
Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.6.5/$injector/nomod?p0=MenuAppX
at angular.min.js:7
at angular.min.js:26
at b (angular.min.js:25)
at Object.module (angular.min.js:26)
at routes.js:4
at routes.js:25
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.6.5/$injector/modulerr?p0=MenuAppX&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.5%2F%24injector%2Fnomod%3Fp0%3DMenuAppX%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A26%3A408%0A%20%20%20%20at%20b%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A25%3A439)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A26%3A182%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A42%3A290%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20gb%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A46%3A251)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(http%3A%2F%2Flocalhost%3A3000%2Flib%2Fangular.min.js%3A22%3A332)
at angular.min.js:7
at angular.min.js:43
at p (angular.min.js:8)
at g (angular.min.js:42)
at gb (angular.min.js:46)
at c (angular.min.js:22)
at Uc (angular.min.js:22)
at xe (angular.min.js:21)
at angular.min.js:333
at HTMLDocument.b (angular.min.js:38)
Index
<!DOCTYPE html>
<html ng-app="MenuAppX">
<head>
<meta charset="utf-8">
<title>Menu App</title>
</head>
<body>
<h1>Welcome to the Chinese Menu Website</h1>
<ui-view></ui-view>
<!-- Libraries -->
<script src="lib/angular.min.js"></script>
<script src="lib/angular-ui-router.min.js"></script>
<!-- Modules -->
<script src="src/MenuApp/menuapp.module.js"></script>
<script src="src/MenuApp/data.module.js"></script>
<!-- 'menuapp' modules artifacts -->
<script src="src/MenuApp/menudata.service.js"></script>
<script src="src/MenuApp/categories.component.js"></script>
<script src="src/MenuApp/items.component.js"></script>
<!-- Routes -->
<script src="src/routes.js"></script>
menuapp module
(function () {
'use strict';
angular.module('MenuAppX', ['data']);
});
data module
(function () {
'use strict';
angular.module('data', ['MenuDataService'])
});
menuapp service
(function () {
'use strict'
angular.module('MenuAppX')
.service('MenuDataService', MenuDataService);
MenuDataService.$inject = ['$http'];
MenuDataService = function($http) {
var service = this;
// var categoryPromise = service.getAllCategory();
// var itemPromise = service.getItemsForCategory();
// get later
service.getAllCategory = function() {
var deferred = $q.defer();
var categoriesResult = $http({
method: "GET",
url: ('https://davids-restaurant.herokuapp.com/categories.json'),
});
deferred.resolve(categoriesResult);
}
service.getItemsForCategory = function(categoryShortName) {
var deferred = $q.defer();
var itemsResult = $http({
method: "GET",
url: (' https://davids-restaurant.herokuapp.com/menu_items.json?category='),
params: {
category: categoryShortName
}
});
deferred.resolve(itemsResult);
}
};
});
categories component
(function () {
'use strict';
angular.module('MenuAppX')
.component('categoriesX', {
templateUrl: 'src/MenuApp/template/categories.template.html',
bindings: {
categoriesR: '<'
}
});
})();
items component
(function () {
'use strict';
angular.module('MenuAppX')
.component('categoriesX', {
templateUrl: 'src/MenuApp/template/categories.template.html',
bindings: {
categoriesR: '<'
}
});
})();
routes
(function () {
'use strict';
angular.module('MenuAppX')
.config(RoutesConfig);
RoutesConfig.$inject = ['$stateProvider', '$urlRouterProvider'];
function RoutesConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'src/MenuApp/template/home.template.html'
})
.state('category', {
url: '/menuCategory',
templateUrl: 'src/MenuApp/template/categories.template.html'
})
.state('items', {
url: '/menuItems',
templateUrl: 'src/MenuApp/template/items.template.html'
})
}
})();
You need to load data module first inorder to load the MenuAppX module because its a dependency, change your order of references as
<script src="lib/angular.min.js"></script>
<script src="lib/angular-ui-router.min.js"></script>
<!-- Modules -->
<script src="src/MenuApp/data.module.js"></script>
<script src="src/MenuApp/menuapp.module.js"></script>
<!-- 'menuapp' modules artifacts -->
<script src="src/MenuApp/menudata.service.js"></script>
<script src="src/MenuApp/categories.component.js"></script>
<script src="src/MenuApp/items.component.js"></script>
<!-- Routes -->
<script src="src/routes.js"></script>

How to use modal in angularjs ui?

I'm trying to use Angular UI modal, but I keep getting an unknown provider error message: "Error: [$injector:unpr]".
I use custom build to minimize the overall size of the file. I have injected the ui dependency in the app when creating it. The build files are added to the index.html page.
//This is the app.js file
(function() {
angular.module('locatorApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']);
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'home/home.view.html',
controller: 'homeCtrl',
controllerAs: 'vm'
})
.when('/about', {
templateUrl: '/common/views/genericText.view.html',
controller: 'aboutCtrl',
controllerAs: 'vm'
})
.when('/location/:locationid', {
templateUrl: '/locationDetail/locationDetail.view.html',
controller: 'locationDetailCtrl',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}
angular
.module('locatorApp')
.config(['$routeProvider', '$locationProvider', config]);
})();
//This is the controller file
(function() {
angular
.module('locatorApp')
.controller('locationDetailCtrl', locationDetailCtrl);
/*Inject $routeParams service into controller to protect from minification*/
locationDetailCtrl.$inject = ['$routeParams', '$uibModal', 'locatorData'];
function locationDetailCtrl($routeParams, $uibModal, locatorData) {
var vm = this;
vm.locationid = $routeParams.locationid;
locatorData.locationById(vm.locationid)
.success(function(data) {
vm.data = {
location: data
};
vm.pageHeader = {
title: vm.data.location.name
};
})
.error(function(e) {
console.log(e);
});
vm.popupReviewForm = function() {
alert("Let's add a review");
};
}
})();
<!-- This is the index.html file-->
<!DOCTYPE html>
<html ng-app="locatorApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocatoR</title>
<link rel="stylesheet" href="/bootstrap/css/amelia.bootstrap.css">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body ng-view>
<script src="/angular/angular.min.js"></script>
<script src="/lib/angular-route.min.js"></script>
<script src="/lib/angular-sanitize.min.js"></script>
<script src="/lib/ui-bootstrap-custom-2.5.0.min.js"></script>
<script src="/lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
<script src="/angular/locator.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/
jquery.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/javascripts/validation.js"></script>
</body>
</html>
//This is the locatorData service
(function() {
/*Data service for pulling data from the API*/
locatorData.$inject = ['$http'];
function locatorData($http) {
var locationByCoords = function(lat, lng) {
return $http.get('/api/locations?lng=' + lng + '&lat=' + lat + '&maxdist=20');
};
var locationById = function(locationid) {
return $http.get('/api/locations/' + locationid);
};
return {
locationByCoords: locationByCoords,
locationById: locationById
};
};
angular
.module('locatorApp')
.service('locatorData', locatorData);
})();
you should use ng-view on a div inside <body>, so script tags will exist after route template is substituted. Then it would be better to reorganize order of script tags you are adding.
At first non-angular script files, then angular, then your sources
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/javascripts/validation.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<script src="/angular/angular.min.js"></script>
<script src="/angular/locator.min.js"></script>
<script src="/lib/angular-route.min.js"></script>
<script src="/lib/angular-sanitize.min.js"></script>
<script src="/lib/ui-bootstrap-custom-2.5.0.min.js"></script>
<script src="/lib/ui-bootstrap-custom-tpls-2.5.0.min.js"></script>
Then use $uibModal service that you've injected:
vm.popupReviewForm = function() {
$uibModal.open({
template: '...html',
//...config from docs
}).then(function(){console.log('closed successfully');})
.catch(function(){console.log('dismissed modal');});
};
Move your script tag either to below of head tag.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LocatoR</title>
<link rel="stylesheet" href="/bootstrap/css/amelia.bootstrap.css">
<link rel="stylesheet" href="/stylesheets/style.css">
// Scripts
</head>
or, outside the ng-view :
<body>
<div ng-view></div>
// scripts here
</body>
Ok, I've finally figured it out. The problem was using incompatible versions of Angular JS and Angular UI.

Module Exceptions in Angularjs and $exceptionHandler

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>

'fn' is not a function with Angular and Webpack

I have just started out attempting to use Webpack to bundle my Angular App. When I have included the essentials I am getting the following error
Argument 'fn' is not a function, got string
I think it's something to do with Angular-Route, but I can't find anything I can see what would be wrong.
My stripped down files are as follows:
./index.html
<!DOCTYPE html>
<html lang="en" ng-app="crewGui">
<head>
<title>GUI</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/stylesheets/styles.css">
<script src="js/dist/vendor.bundle.js"></script>
<script src="bower_components/Chart.js/Chart.js"></script>
<script src="bower_components/angular-chart.js/dist/angular-chart.js"></script>
<script src="bower_components/angular-busy/dist/angular-busy.min.js"></script>
<script src="js/dist/app.bundle.js"></script>
</head>
<body class="container-fluid">
<header class="row">
<div class="logo col-xs-6">
<img src="images/logo_alt.png" class="img-responsive" alt"logo">
</div>
</header>
<div id="content">
<div class="container-fluid">
<ng-view></ng-view>
</div>
</div>
<footer class="row">
<div class="copyright col-xs-12">©</div>
</footer>
</body>
</html>
./module.js
'use strict';
var angular = require('angular');
var ngRoute = require('angular-route');
angular
.module('crewGui', [
'ngRoute'
]
);
require('./');
require('./services');
require('./controllers');
./index.js
'use strict';
var angular = require('angular');
var ngRoute = require('angular-route');
angular
.module('crewGui')
.config('Config', require('./config'))
.run('Run', require('./run'));
./run.js
'use strict';
Run.$inject = ['$http'];
function Run($http) {
$http.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
$http.defaults.headers.common['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT';
$http.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
$http.defaults.headers.common['Accept'] = 'application/json';
$http.defaults.headers.common.Authorization = "Basic AWORKINGAPIKEY";
};
module.exports = Run;
./config.js
'use strict';
Config.$inject = ['$routeProvider'];
function Config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/dashboard.html',
controller: 'DashboardController',
controllerAs: 'dashboard'
})
.otherwise({
redirectTo: '/'
});
};
module.exports = Config;
./services/index.js
'use strict';
var angular = require('angular');
var ngRoute = require('angular-route');
angular
.module('crewGui')
.service('GetData', require('./get_data_service'));
./services/get_data_service.js
'use strict';
GetData.$inject = ['$http'];
function GetData($http) {
var self = this;
self.getData = function() {
return $http.get("https://aworkingurl")
.success(function (data, status, headers, config) {
return data;
})
.error (function (data, status, headers, config) {
return status;
});
};
};
module.exports = GetData;
./controllers/index.js
'use strict';
var angular = require('angular');
var ngRoute = require('angular-route');
angular
.module('crewGui')
.controller('DashboardController', require('./controller_dashboard'));
./controllers/controller_dashboard.js
'use strict';
DashboardController.$inject = ['$scope', 'GetData'];
function DashboardController($scope, GetData) {
var self = this;
GetData.getData()
.then(function(data){
self.flightData = data.data;
});
};
module.exports = DashboardController;
Any constructive help would be much appreciated. Please let me know if there;'s anything else you need. And i probably don't need to be requiring ngRoute all over the place. Clutching at straws at this point.
Many thanks.
In index.js try removing 'Config' and 'Run' so the lines look like this:
.config(require('./config'))
.run(require('./run'));
The error was suggesting that the first argument needs to be a function instead of a string :)
For everyone who comes here looking for a solution to the error, please check your global variables in the console, and the name of your remotes for collision. For us, the problem was that we called our remote navigator, but in the global context, there was already a variable defined with that name.

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:

Categories