AngularJS unknown provider: $routeProviderProvider - javascript

I'm struggling with this unknown provider error and just wondering what I'm doing wrong. Have this structure:
in main.js
'use strict';
angular.module('myApp')
.controller('MainCtrl', ['navService', function (navService) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
this.active = false;
navService.getPosition();
}]);
In index html I have ng-controller="MainCtrl"
And finally in navService:
angular.module('myApp')
.factory('navService', ['$routeProvider', '$location', function ($routeProvider, $location) {
function getPosition() {
/*code here */
}
return {
getPosition: getPosition
};
}]);
In main app.js
angular
.module('cavyrApp', [
'ngAnimate',
'ngCookies',
'ngMessages',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
]).config...........

$routeProvider is a provider - you can not inject it into factory/service. You can inject it to the config method only - to configure the service it will provide:
module.config(function($routeProvider) {
// configure the routes here
});

You should inject your factroy like this:
angular.module('myApp',['ngRoute']); //route inject
and the controller:
angular.module('myApp').controller('MainCtrl', function(navService) {
});

Related

Angular Module Config block is never getting called

Angular Config module is not getting invoked.
In the below code snippet, app.state.js is getting invoked, but the config part it's not. Please help me out on this.
This is used in a jhipster application
**app.module.js :**
(function() {
'use strict';
var app= angular
.module('IloadsApp', [
'ngStorage',
'tmh.dynamicLocale',
'pascalprecht.translate',
'ngResource',
'ngCookies',
'ngAria',
'ngCacheBuster',
'ngFileUpload',
'ui.bootstrap',
'ui.bootstrap.datetimepicker',
'ui.router',
'infinite-scroll',
// jhipster-needle-angularjs-add-module JHipster will add new module here
'angular-loading-bar'
]);
app.run(run);
run.$inject = ['stateHandler', 'translationHandler'];
function run(stateHandler, translationHandler) {
stateHandler.initialize();
translationHandler.initialize();
}
})();
**app.state.js :**
(function() {
'use strict';
angular
.module('IloadsApp')
.config(stateConfig);
stateConfig.$inject = ['$statePsrovider'];
alert ("before Inside ");
function stateConfig($stateProvider) {
alert ("Inside ");
$stateProvider.state('app', {
abstract: true,
views: {
'navbar#': {
templateUrl: 'app/navbar/navbar.html',
controller: 'NavbarController',
controllerAs: 'vm'
}
},
resolve: {
authorize: ['Auth',
function (Auth) {
return Auth.authorize();
}
],
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('global');
}]
}
});
}
alert("After");
})();

angularjs app not working after code concatination

I have and angularjs app.I want to concatenate all the JS files to a single file.I'm currently trying to use Grunt.js to setup an automatic build process for concatenating JavaScript files.
However my app runs without any error before concatenation.But after concatinating the files my app throws Error: $injector:modulerr
Module Error.
Below is my code after minification
angular.module('myApp', []);
var app = angular
.module('myApp', [
'ngRoute'
]);
app.config(function ($routeProvider) {
'use strict';
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'mainCntrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'aboutCntrl',
controllerAs: 'about'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('mainCntrl',['$scope', function ($scope) {
'use strict';
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
}]);
app.controller('aboutCntrl',['$scope', function ($scope) {
'use strict';
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
}]);
Any help appreciated.Thanks :)
You need to strictly follow either Inline Array Annotation of DI or $inject Property Annotation while minifying js files.
app.config(function ($routeProvider) {
'use strict';
//code
});
should be changed to below code.
Inline Array Annotation
app.config(['$routeProvider', function ($routeProvider) {
'use strict';
//code as is
}]);
$inject Property Annotation
var config = function($routeProvider) {
'use strict';
//code as is
}
config.$inject = ['$routeProvider'];
app.config(config);
Seems like the config line is your problem, try app.config(['$routeProvider', function ($routeProvider) { ... }]);
Yes, your annotation is not right. It should be
app.config(['$routeProvider', function ($routeProvider) {
'use strict';
//code
}]);
Use ng-annotate as a safe, clean and simple solution.
What it does is that when you grunt it'll annotate your definitions the proper way, so you don't have to deal with Angular's quirky way.
Run ng-annotate on
app.config(function($routeProvider) {
'use strict';
//code
});
and it'll auto-complete it for minification:
app.config(["routeProvider", function($routeProvider) {
'use strict';
//code
}]);
You can also add another step to your build workflow - grunt-ng-annotate in that case you will be able to skip almost all strict DI annotations. With this plugin you can simplify services/controllers definitions e.g.:
app.controller('mainCntrl', function ($scope) {
'use strict';
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
It is extremely helpful when you heave a long list of services to inject into controller or another service. You don't have to remember to put each dependency twice.

Read JSON with Angular, undefined service

I am trying to read a JSON data from a file using angular factory and service. But Angular can't see my defined service. Here is my factory:
//jsonService.js
angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource) {
alert($resource)
return $resource('example.json',{}, {
getData: {method:'GET', isArray: false}
});
});
And my controller:
//app.js
'use strict';
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'jsonService'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]).
controller('mainController', ['JsonService', function($scope, JsonService){
JsonService.getData(function(data) {
console.log("Test");
$scope.length = data.length;
})}]);
And I get:
"Error: JsonService is undefined"
You're injecting 'JsonService' as the first parameter of your function, but you are using the JsonService as the 2nd parameter of your function.
Should be ['JsonService', '$scope', function($scope, JsonService){ or if $scope not needed then ['JsonService', function(JsonService){
This line in app.js should look like
controller('mainController', ['$scope','JsonService', function($scope, JsonService){

Angular Controllers Firing off more than once. Only certain ones

I have markup that has the following and then I have different sections of the app defined in different files. The problem I am running into is that the controllers that are on the main app page on load causes each of the nested controllers to run more than once. Any states that I change to with a click of the button are fine but these fire off 2-3 times each.
<html ng-app="myApp">
<body ng-controller="myController">
<div ng-controller="dashController">
<div ng-controller="listController">
</div>
</div>
</body>
</html>
My App.js
var myApp = angular.module('myApp', [
'user.profile',
'myApp.controllers',
'myApp.directives',
'ngCookies',
'ngAutocomplete',
'ui.router'
]).config(function($stateProvider, $urlRouterProvider, $locationProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$urlRouterProvider.otherwise('/');
$stateProvider.
state('app', {
url: '/app',
templateUrl: '/views/homepage',
controller: 'MyCtrl1'
});
$locationProvider.html5Mode(true);
});
myApp.controllers
angular.module('myApp.controllers', ['ui.router','ngCookies']).
controller('myController', function ($scope, $http,$cookies) {
$scope.message = 'nothing to see here, move along';
if ($cookies.userdata) {
$cookies.userdata = $cookies.userdata.replace("j:", "");
console.log($cookies);
}
});
user.profile.js
angular.module('user.profile', [
'user.controllers',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'nouislider',
'ui.router',
'ui.bootstrap',
'ngLinkedIn'
])
.config(function($stateProvider, $urlRouterProvider, $locationProvider,$interpolateProvider, $linkedInProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$linkedInProvider.set('appKey', '753pos06f998t3')
.set('scope', 'r_fullprofile');
//.set('authorize', true);
$locationProvider.html5Mode(true);
$stateProvider
.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
});
user.controllers.js
angular.module('user.controllers', ['ui.router', 'ngAutocomplete', 'nouislider', 'ui.bootstrap', 'ngCookies', 'ngLinkedIn', 'angularFileUpload','cgPrompt'])
.directive('onLastRepeat', function () {
return function (scope, element, attrs) {
if (scope.$last) setTimeout(function () {
scope.$emit('onRepeatLast', element, attrs);
}, 1);
};
}).
controller('dashController', function ($scope, $state, $modal, $log, $http, $cookies) {
$scope.user = [];
}).
controller('listController', function ($scope, $http, $cookies) {
});
My app also doesn't initialize unless I run angular.bootstrap(document, ["myApp"]);
I don't think it is having the controller defined in the $stateProvider and the DOM... if I remove from the DOM none of the ng-clicks work even after the controller fires... also I have an ng-click that changes the state and it's controller is defined in the stateProvider and in the DOM and it does not fire twice... what is does is kick off the two other controllers again first before proceeding with it's action though.
The issue is that you are defining your controllers with the routeProvider / stateProvider ie:
$stateProvider.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
an you are redifining them in the DOM using
<div ng-controller="dashController">
remove one or the other but don't use the two at the same time, I'd suggest to remove the one declared in the DOM, ng-controller="dashController"
cheers

Error with PouchDB: TypeError: angular.factory is not a function

I'm trying to figure out how to use PouchDB in AngularJS. I'm trying to follow these instructions https://github.com/wspringer/angular-pouchdb
I think I'm having a problem understanding the syntax for creating factories and/or services. I get as far as the section on "Interacting with the database"
app.js
'use strict';
angular
.module('myappApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'pouchdb'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
angular.factory('someservice', function(pouchdb) {
// Do something with pouchdb.
var db = pouchdb.create('testdb');
pouchdb.destroy('testdb');
db.put({_id: 'foo', name: 'bar'});
});
When I add the "db.put", The message I see in the browser's console is:
[15:17:45.343] TypeError: angular.factory is not a function # http://127.0.0.1:9000/scripts/app.js:21
The angular object does not have a factory method, so it will returned as undefined.
Try putting it on the object returned by the module method.
angular
.module('myappApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'pouchdb'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
// note the difference here, it is using the object returned by module() and config()
.factory('someservice', function(pouchdb) {
// Do something with pouchdb.
var db = pouchdb.create('testdb');
pouchdb.destroy('testdb');
db.put({_id: 'foo', name: 'bar'});
});
In addition, I was able to adapt this code example to test the DB is working
http://plnkr.co/edit/M2K7no75zonXKcXKF9Sc?p=preview
app.js
'use strict';
angular
.module('myappApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'pouchdb'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.factory('MyModel', function(pouchdb) {
return new pouchdb.create('mydb');
})
.run(function (){
var db = new PouchDB('mydb');
db.info().then(function(info) {
if (info.doc_count < 2) {
db.post({display: 'Hello'});
db.post({display: 'World'});
}
});
});
main.js
'use strict';
angular.module('myappApp')
.controller('MainCtrl', function ($scope, MyModel) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
MyModel.info().then(function(info) {
$scope.numOfDocs = info.doc_count;
});
$scope.options = {
db: MyModel,
name: 'Visitor'
};
$scope.db = MyModel;
});
main.html
<p>Hello {{options.name}}! There are {{numOfDocs}} docs in your Pouch</p>
<p>Root scope:</p>
<ul>
<li pouch-repeat="item in db" ng-bind="item.display"></li>
</ul>
<p>Child scope:</p>
<ul>
<li pouch-repeat="item in options.db" ng-bind="item.display"></li>
</ul>

Categories