AngularJS 1.2.9 ngRoute "unknown provider $routeProvider error with requireJS - javascript

I'm using angularJS-1.2.9 and angular-route-1.2.9 to set up routes for my application , i'm using requireJS as the dependency loader and modularize the code . I have added the ngRoute dependency into the AngularJS config , but still getting this following error in the chrome console Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:Error: [$injector:unpr] Unknown provider: $routeProvoider
Here is my code
main.js
require.config({
baseUrl: './js',
paths: {
angular: 'libs/angular-1.2.9',
angularRoute: 'libs/angular-route-1.2.9'
},
shim: {
'angularRoute': {
deps: ['angular'],
exports: 'angularRoute'
},
'angular': {
exports: 'angular'
}
}
});
require(['angular', 'angularRoute'], function (angular, angularRoute) {
'use strict';
var app = angular.module('myApp', ['ngRoute']);
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
app.controller('indexController', function ($scope, $http) {
console.log('inside index');
});
app.config(
function ($routeProvoider) {
$routeProvider.
when('/', {
templateUrl: 'index_content.html',
controller: 'indexController'
})
});
});
Here are my html files
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script data-main="js/main.js" src="js/libs/require.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
index_content.html
<p>inside Index content</p>
<h1>testing the ang routes
Whats the issue here ?? Why is it still giving away the above mentioned error ?? How to fix this ??

There is a typo error on $routeProvider in the code I have rectified and placed the code below:
Code Snippet:
require(['angular', 'angularRoute'], function (angular, angularRoute) {
'use strict';
var app = angular.module('myApp', ['ngRoute']);
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});
app.controller('indexController', function ($scope, $http) {
console.log('inside index');
});
app.config(
function ($routeProvider) { //One typo here
$routeProvider.
when('/', {
templateUrl: 'index_content.html',
controller: 'indexController'
})
});
});

app.config(
function ($routeProvider) {
$routeProvider.
when('/ResourceItem/:RE_RestoId',{
templateUrl:'./partials/state-view.html',
controller: function ($routeParams, ResourceService) {
this.params = $routeParams;
var that = this;
ResourceService.getResourceItem(this.params.RE_RestoId || "").success(function (data) {
that.items = data;
})
this.addItemTo = function (resource)
{
if(!resource.items)
{
resource.items = [];
}
resource.items.push({TA_Code: this.newResourceItem });
this.newResourceItem="";
};
},
controllerAs:'ResourceItemCtrl'
});
});

Related

AngularJS Routing Function is not working

My Angular Routing Function is not working - There is a page load, but without the 'home.html' file. This is my code:
Index.html
<html ng-app="App" class="no-js" lang="en" >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-cloak>
<div ng-controller="main">
<div ng-view></div>
</div>
</body>
</html>
app.js
(function () {
'use strict';
angular
.module('App', ['ngRoute'])
.controller('$routeProvider', router)
.controller('main', main);
function router($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '_pages/home.html',
controller: 'main'
});
};
function main ($scope) {
console.log("done");
}
Angular $providers working just in config state.
Eg:
angular
.module('App', ['ngRoute'])
.config(['$routeProvider', router]);
function router($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '_pages/home.html',
controller: 'main'
});
};
The route configuration is done in config and not controller. Change your code as below:
(function () {
'use strict';
angular
.module('App', ['ngRoute'])
.config(router)
.controller('main', main);
function router($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '_pages/home.html',
controller: 'main'
});
};
function main ($scope) {
console.log("done");
}
});

Angular.js controller that uses multiple services

I can't seem to figure how to inject multiple services into a controller.
I have listed my files here:
index.html file:
<script src="'./angular/angular.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>
<script src="'./angular-route/angular-route.js'></script>
<script src='./app/app.js'></script>
<script src='./app/welcome/welcome.js'></script>
<script src='./app/controls/questions.js'></script>
<script src='./app/services/questionsdata.js'></script>
<script src='./app/services/getsong.js'></script>
console.log error:
Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=getsongProvider%20%3C-%20getsong%20%3C-%20QuestionsCtrl
at Error (native)
at http://localhost:8000/static/angular/angular.min.js:6:416
at http://localhost:8000/static/angular/angular.min.js:43:7
at Object.d [as get] (http://localhost:8000/static/angular/angular.min.js:40:270)
at http://localhost:8000/static/angular/angular.min.js:43:69
at d (http://localhost:8000/static/angular/angular.min.js:40:270)
at e (http://localhost:8000/static/angular/angular.min.js:41:1)
at Object.instantiate (http://localhost:8000/static/angular/angular.min.js:41:364)
at http://localhost:8000/static/angular/angular.min.js:87:42
at link (http://localhost:8000/static/angular-route/angular-route.js:977:26) <section class="container-fluid ng-scope" id="main" ng-view="">
My app.js file:
(function(){
'use strict';
angular.module('myApp', ['ngRoute', 'myApp.welcome', 'myApp.questions' ])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
redirectTo: '/welcome'
})
.when('/welcome', {
templateUrl: 'static/app/welcome/welcome.html',
controller: 'WelcomeCtrl'
})
.when('/questions', {
//templateUrl: 'static/app/questions/questions.html',
templateUrl: 'static/app/views/questions.html',
//controllerAs: 'question',
controller: 'QuestionsCtrl'
})
.otherwise('/')
});
})();
My controller file:
(function () {
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
function QuestionCtrl(questionsdata,getsong) {
var vm = this;
var data = {
params: "1,1"
};
....
My questionsdata (first service) file:
(function () {
'use strict';
angular
.module('myApp.questions')
.factory('questionsdata', questionsdata);
function questionsdata() {
var service = {
getQuestions: getQuestions
};
return service;
.....
My get song (second service) file
(function () {
'use strict';
angular
.module('myApp.questions')
.factory('getsong',getsong);
function getsong($http, $window, $interval) {
var service = {
getId: getId,
getMySong: getMySong
};
return service;
....
That's ain't working.
When I change my controller file to use only the questionsdata service as follows:
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
function QuestionCtrl(questionsdata) {
It's working well. But when trying to use only the get song service as follows:
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
function QuestionCtrl(getsong) {
It ain't working as well.
Weird, right? What am I missing?
Try using the inject method:
'use strict';
angular
.module('myApp.questions', ['ngRoute', 'ngSanitize'])
.controller('QuestionsCtrl', QuestionCtrl);
QuestionCtrl.$inject = ['getsong', 'questiondata'];
function QuestionCtrl(getsong, questiondata){
Try this in index.html:
<script src="'./angular/angular.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>
<script src="'./angular-route/angular-route.js'></script>
<script src='./app/controls/questions.js'></script>
<script src='./app/welcome/welcome.js'></script>
<script src='./app/app.js'></script>
<script src='./app/services/getsong.js'></script>
<script src='./app/services/questionsdata.js'></script>
Because myApp depends on myApp.welcome and myApp.questions, so you have to put them first.

AngularJS: Uncaught Error: $injector:modulerr Failed to instantiate module

I am trying to include several directives in as dependencies. Everything was working fine until I added a new directive called classificationview. its just an directive which will i will use somewhere later.
I am getting the error of :
Uncaught Error: [$injector:modulerr] Failed to instantiate module mainapp due to:
Error: [$injector:modulerr] Failed to instantiate module ald.classificationview due to:
Error: [$injector:nomod] Module 'ald.classificationview' 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.
The classification directive:
/**
*
*/
var classificationViewModule = angular.module('ald.classificationview',[]);
classificationViewModule.factory('classificationAPI',function(){
return {
getClassification:function($http){
//TODO add URL
var url = "/Classification?artifactId=6450"
return $http({
method: 'GET',
url: url
});
}
};
});
classificationViewModule.directive('classification', function () {
return {
restrict: 'EA',
scope: {},
replace: true,
link: function ($scope, element, attributes) {
},
controller: function ($scope, $http, classificationAPI) {
classificationAPI.getClassification($http).success(function(data,status){
//TODO Add required binding
$scope.artifactClassification = data;
}).error(function(data,status){
if (404==status){
alert("no text");
} else {
alert("bad stuff!");
}
});
},
//TODO add template url
templateUrl: "classificationview.html"
};
});
The main.js file :
var theApp = angular.module('mainapp', [
'ald.documentlist',
'ald.hierarchylist',
'ald.hierarchyviewer',
'ald.documentdisplay',
'ald.artifactlist',
'ald.classificationview',
'ngRoute'
]);
var controllers = {};
var directives = {};
controllers.tabsController = function ($scope, $location, $http) {
$scope.onClickTab = function (tabUrl) {
$scope.removePadding();
$location.$$search = {};
if (tabUrl == 'Hierarchy') {
$location.path("/hierarchy");
}
else if (tabUrl == 'Artifacts') {
$location.path("/artifacts");
}
else {
$location.path("/documents");
}
};
$scope.removePadding = function() {
$("#documentTab").css("padding", "0px");
$("#hierarchyTab").css("padding", "0px");
$("#artifactTab").css("padding", "0px");
};
};
controllers.IndexController = function ($scope, $http) {
};
controllers.DocumentsCentricViewCtrl = function ($scope, $http) {
$("#tabs").tabs( "option", "active", 0 );
};
controllers.DocumentDisplayViewCtrl = function ($scope, $http) {
$("#tabs").tabs( "option", "active", 0 );
};
controllers.HierarchyCentricViewCtrl = function ($scope, $http) {
$("#tabs").tabs( "option", "active", 1 );
};
controllers.ArtifactsCentricViewCtrl = function ($scope, $http) {
$("#tabs").tabs( "option", "active", 2 );
};
directives.panelTabs = function() {
return {
restrict: 'A',
link: function($scope, elm, attrs) {
var jqueryElm = $(elm[0]);
$(jqueryElm).tabs()
$scope.removePadding();
}
};
};
theApp.controller(controllers);
theApp.directive(directives);
theApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/documents', {
templateUrl: 'documentscentricview.html',
controller: 'DocumentsCentricViewCtrl'
}).
when('/hierarchy', {
templateUrl: 'hierarchycentricview.html',
controller: 'HierarchyCentricViewCtrl'
}).
when('/artifacts', {
templateUrl: 'artifactscentricview.html',
controller: 'ArtifactsCentricViewCtrl'
}).
when('/documents/:doc', {
templateUrl: 'documentdisplay.html',
controller: 'DocumentDisplayViewCtrl'
}).
otherwise({
/*
templateUrl: 'indexview.html',
controller: 'IndexController'
*/
redirectTo: '/documents'
});
}]);
The source of the javascript file is given in index file:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="layout" content="main"/>
<title>The Analyzer Engine and SDX Analysis UI</title>
%{--<script type="text/javascript">--}%
%{----}%
%{--</script>--}%
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<asset:link rel="icon" href="images/*" type="image/png"/>
<asset:stylesheet src="main.css"/>
<asset:javascript src="main.js"/>
<asset:javascript src="ald/documentlist/documentlist.js"/>
<asset:javascript src="ald/hierarchylist/hierarchylist.js"/>
<asset:javascript src="ald/hierarchyviewer/hierarchyviewer.js"/>
<asset:javascript src="ald/documentdisplay/documentdisplay.js"/>
<asset:javascript src="ald/artifactlist/artifactlist.js"/>
<asset:javascript src="ald/classificationview/classificationview.js"/>
</head>
<body>
<div ng-app="mainapp" class="tabWidth">
<div ng-controller="tabsController">
<div id="tabs" panel-Tabs>
<ul>
<li>Document</li>
<li>Hierarchy</li>
<li>Clauses, Terms and Titles</li>
</ul>
<div id="emptyDiv"></div>
</div>
</div>
<div ng-view></div>
</div>
</body>
</html>
It looks like the arguments to the link and controller functions in your directive are incorrect. Try this:
// 'scope' not '$scope'
link: function (scope, element, attributes) {
// Don't inject $http or your other dependency into the controller function. Use the //constructor function of the directive. See below:
controller: function ($scope)
classificationViewModule.directive('classification', function ($http, ClassificationAPI) {

AngularJs $injector:modulerr after RequireJS r.js optimization

The AngularJS-RequireJS app im building is throwing Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:unpr] Unknown provider: e error after r.js optimization . The problem didnt exist before . I followed a similar question at this link and added mainConfigFile to the build file , but still the problem persists . Here are the codes the respective files
build.js
({
mainConfigFile:'js/main.js',
appDir: "./",
baseUrl: "js",
dir: "/home/karthic/optimized-test",
modules: [
{
name: "main"
}
]
})
main.js
require.config({
baseUrl: './js',
paths: {
angular: 'libs/angular-1.2.9',
angularRoute: 'libs/angular-route-1.2.9'
},
shim: {
'angularRoute': {
deps: ['angular'],
exports: 'angularRoute'
},
'angular': {
exports: 'angular'
}
}
});
require(['angular', 'controller', 'ang_when_routes', 'angularRoute'], function(angular, controller, angWhenRoutes, angularRoute) {
'use strict';
var app = angular.module('myApp', ['ngRoute']);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
angWhenRoutes.initRoutes(app);
controller.controllerInit(app);
});
controller.js
define(function() {
function controllerInit(app) {
console.log('inside func cont');
app.controller('mapApp', function($scope, $http, $location) {
console.log('inside mapp,testing r.js optimizer');
});
}
return {
controllerInit: controllerInit
}
});
ang_when_routes.js
define(function() {
function initRoutes(app) {
app.config(
function($routeProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
$routeProvider.
when('/', {
templateUrl: 'index_content.html',
controller: 'mapApp'
})
});
}
return {
initRoutes: initRoutes
}
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Optimizer error</title>
<script data-main="js/main.js" src="js/libs/require.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>
index_content.html
<p>Testing the r optimizer</p>
It'll be really helpful for me if the error can be fixed
Here is the answer as suggested by #radimKohler in the first comment . To avoid issues with angularJS during minification Inline array Annotation has to be used as referred in the Angular Documentation . Here is the modified code after the change
controller.js
define( function () {
function controllerInit(app) {
console.log('inside func cont');
app.controller('mapApp',['$scope','$http','$location', function ($scope, $http, $location) {
console.log('inside mapp,testing r.js optimizer');
}]);
}
return {
controllerInit: controllerInit
}
});
ang_when_routes.js
define(function(){
function initRoutes(app){
app.config(['$routeProvider','$httpProvider',
function($routeProvider,$httpProvider){
$httpProvider.defaults.withCredentials = true;
$routeProvider.
when('/',{
templateUrl:'index_content.html',
controller:'mapApp'
})
}]);
}
return {
initRoutes:initRoutes
}
});

Integrating AngularJS with RequireJS

Due This Article I try to create an application with AngularJS and RequireJS!
I can load angular library... create module and export it to external files! It's ok!
But the problem is I can't create configuration and controllers for my module both in main application file and external files!
Another issue is I can't load views and controllers in app.js via $routeProvider!!
(Sorry for grammer problems!)
app.js:
require.config({
baseUrl: "/angularjs/js",
paths: {
"angular": "libs/angular.min"
},
shim: {
"angular": {
exports: "angular"
}
}
});
define('app', ['angular'], function(angular){
var app = angular.module('myApp', []);
app.config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
controller: 'HomeCtrl'
templateUrl: 'views/home.html'
});
});
return app;
});
require(["app", "controllers/homeController"]);
controllers/homeController.js:
require(["app"], function(app) {
app.controller("HomeCtrl",
function($scope) {
$scope.message = "Hello World!";
}
);
});
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8" />
<title>Angular.js</title>
<script type="text/javascript" data-main="js/" src="js/libs/require.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
views/home.html:
<div ng-controller="HomeCtrl">
<h1>{{messge}}</h1>
</div>
Here is my version of your example. With a few changes it works fine.
It is better to bootstrap AngularJs application manually, when RequireJs.
I separated app.js file in two: main.js - with configuration of RequireJs and app.js - with AngularJs module declaration. Later, this module is used by homeController for declaration of controller. Then, the controller is required in main.js and the application is bootstrapping.
I do the angular and requireJS integration placing NG_DEFER_BOOTSTRAP! flag and have separate files for my app config and routing like in:
require.config({
baseUrl: 'js/',
paths: {
angular: '../lib/bower_components/angular/angular.min',
angularRoute: '../lib/bower_components/angular-route/angular-route.min'
},
shim: {
'angular': {
'exports': 'angular'
},
'angularRoute':{
'deps': ['angular']
}
},
priority: [
'angular'
]
});
//https://docs.angularjs.org/guide/bootstrap
window.name = 'NG_DEFER_BOOTSTRAP!';
require([
'angular',
'app',
'routes'
], function(angular, app, routes) {
'use strict';
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
angular.resumeBootstrap([app['name']]);
});
});
app.js:
define([
'angular',
'filters',
'services',
'directives',
'controllers',
'animations',
'angularRoute'
], function (angular) {
'use strict';
return angular.module('myapp', [
'ngRoute',
'ngCookies',
'ngAnimate',
'myapp.services',
'myapp.directives',
'myapp.filters',
'myapp.controllers',
'myapp.animations'
]);
});
and routes.js:
define(['angular', 'app'], function(angular, app) {
'use strict';
return app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
}).
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
otherwise({
redirectTo: '/home'
});
}])
});
hope this helps in your scenario.

Categories