Error: $injector:unpr Unknown Provider - angularjs

I have app.js code like this
var MYApp = angular.module('myApp', ['ngRoute', 'myAppServices', 'ngSanitize'])
.config(myRouter);
angular.module('myAppServices', ['ngResource'])
.factory('GridsAPI', function($resource) {
return {
Users: $resource('/MY/system/users/grid'),
Groups: $resource('/MY/system/groups/grid'),
GroupList: $resource('/MY/system/getGroupList')
};
});
MYApp.controller('CreateUserController', ['$scope', 'groupList', function($scope, groupList) {
$scope.test = 'Hello';
$scope.groups = groupList;
debugger; //here I am getting correct values of test and groups
}]);
function myRouter($routeProvider) {
$routeProvider
.when('/users/create', {
templateUrl: '/MY/system/users/create',
controller: 'CreateUserController',
resolve: {
groupList: function(GridsAPI) {
return GridsAPI.GroupList.get().$promise;
}
}
});
}
here is my html
<div class="white-box" ng-controller="CreateUserController">
<h1>{{test}}</h1>
<pre>{{ groups | json }}
</div>
and in browser I am getting this, no binding at all, what I am missing??
{{test}}
{{ groups | json }}
at debugger I am getting object correctly... see the screenshot

Your resolve returns a promise. This promise will contain your groups as soon as they arrive.
MYApp.controller('CreateUserController', ['$scope', 'groupListPromise', function($scope, groupList) {
$scope.test = 'Hello';
$scope.groups = [];
groupListPromise.then(function(groupList){
$scope.groups = groupList;
});
debugger; //here I am getting correct values of test and groups
}]);
function myRouter($routeProvider) {
$routeProvider
.when('/users/create', {
templateUrl: '/MY/system/users/create',
controller: 'CreateUserController',
resolve: {
groupListPromise: function(GridsAPI) {
return GridsAPI.GroupList.get().$promise;
}
}
});
}

Related

Unknown provider: DashboardServiceProvider <- DashboardService <- DashboardController

even if I read a lot of solutions according my problem, still to have this Error.
This is my Controller:
#Controller
#RequestMapping( "/dashboard" )
public class DashboardController {
#RequestMapping( value = "", method = RequestMethod.GET )
public HttpEntity<String> dashboard() {
SimpleDateFormat sdf = new SimpleDateFormat( "dd-MM-yyyy" );
return new HttpEntity<String>( "Today is " + sdf.format( new Date() ) );
}
}
this is my index.jsp
<body ng-app="dashboard">
<div ng-controller="DashboardController">
<p>Nome: <input type="text" ng-model="nome"></p>
<p>Cognome: <input type="text" ng-model="cognome"></p>
<input type="button" value="LOGIN" ng-click="login()"/>
</div>
<jsp:include page="includes.jsp"></jsp:include>
<div ng-show="value==1">
{{data}}
</div>
<div ng-show="value==0">
{{ResponseDetails}}
</div>
</body>
this is my module
var Dashboard = angular.module( 'dashboard', ['DashboardService'] )
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/dashboard', {
templateUrl: '/WEB-INF/pages/dashboard.jsp',
controller: 'DashboardController'
});
}]);
my service
Dashboard.factory('DashboardService', function ($http) {
return {
dashboard: function(successCallback, errorCallback) {
$http.get("/dashboard")
.success(
function (response) {
$scope.data = response;
}
).error(
function (response) {
$scope.data = "ERROR!";
}
)
}
}
});
and finally my controller
angular.module("dashboard", [])
.controller( 'DashboardController', function ($scope, DashboardService) {
$scope.nome = "Daniele";
$scope.cognome = "Comandini";
var data = {
nome: $scope.nome,
cognome: $scope.cognome
};
$scope.value = 0;
var login = function() {
alert("LOGIN ON DASHBOARD");
DashboardService.dashboard();
};
$scope.login = login;
});
My JSP page must only send the request to the DashBoardcontroller, that it has the return the page dashboard.jsp with the current date.
You must not inject dependencies in your module. Dependencies like service, factory have to be injected in controllers. By the way, don't forget to inject ngRoute.
Module becomes:
var Dashboard = angular.module( 'dashboard', ['ngRoute'] )
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/dashboard', {
templateUrl: '/WEB-INF/pages/dashboard.jsp',
controller: 'DashboardController'
});
}]);
Your controller code is good, just one thing: if you want to use a code compiler like Grunt, Gulp or Webpack, don't forget to add your dependencies as strings:
angular.module('dashboard')
.controller( 'DashboardController', ['$scope', 'DashboardService'], function ($scope, DashboardService) {
I copied your controller with the service injection
.controller( 'DashboardController', ['$scope', 'DashboardService'], function ($scope, DashboardService) {
but in the end I had to write this
Dashboard.controller( 'DashboardController', ['$scope', 'DashboardService' , function ($scope, DashboardService) {
$scope.nome = "Daniele";
$scope.cognome = "Comandini";
var data = {
nome: $scope.nome,
cognome: $scope.cognome
};
$scope.value = 0;
var login = function() {
alert("LOGIN ON DASHBOARD");
DashboardService.dashboard();
};
$scope.login = login;
}]);
I mean I had to include the function into [], and not outside.

AngularJS: Error on Factory and routeProvider

In "routeProvider" I have the "objectStats" on resolve, but my controller does not seem to understand it. (I found several problems like on stackoverflow, but no solution solved my error)
My code:
var app = angular.module('AppLearning', ['ngRoute','easypiechart']);
app.config(['$routeProvider',function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'index.html',
controller: 'AppCtrl',
resolve: {
objectStats: function(statsFactory) {
return statsFactory.getStatsFollow();
}
}
}).
otherwise({
redirectTo: '/home'
});
}]);
app.controller('AppCtrl', ['$scope', '$http', 'objectStats', function ($scope, $http, objectStats) {
$scope.statsUnfollow = objectStats.data;
$scope.percent = 65;
$scope.pieOptions = {
animate:{
duration:2000,
enabled:true
},
trackColor: '#e5e5e5',
barColor: '#3da0ea',
scaleColor:false,
lineWidth:5,
lineCap:'square'
};
}]);
app.factory('statsFactory', ['$http', function($http) {
return {
//Code edited to create a function as when you require service it returns object
//by default so you can't return function directly. That's what understand...
getStatsFollow: function (type) {
var q = $q.defer();
$http.get('/api/stats/follow').success(function (data) {
q.resolve(function() {
var settings = jQuery.parseJSON(data);
return settings[type];
});
});
return q.promise;
}
}
}]);
Error: [$injector:unpr] Unknown provider: objectStatsProvider <- objectStats
http://errors.angularjs.org/1.2.9/$injector/unpr?p0=objectStatsProvider%20%3C-%20objectStats
minErr/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:78:12
createInjector/providerCache.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3546:19
getService#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3673:39
createInjector/instanceCache.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3551:28
getService#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3673:39
invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3700:1
instantiate#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3721:23
$ControllerProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6772:18
nodeLinkFn/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6185:34
forEach#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:310:11
nodeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:6172:11
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5636:15
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5639:13
compositeLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5639:13
publicLinkFn#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:5541:30
bootstrap/doBootstrap/https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1304:11
$RootScopeProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:11955:16
$RootScopeProvider/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:12055:18
bootstrap/doBootstrap/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1302:9
invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:3710:14
bootstrap/doBootstrap#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1300:1
bootstrap#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1314:1
angularInit#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:1263:5
#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js:20555:5
b.Callbacks/c#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:7852
b.Callbacks/p.fireWith#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:8658
.ready#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:3264
H#https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:693

how to call the method of controller in routeProvider resolve function

I wanna update the data and then show the view bound with this controller, the code is as follow
angular.module('myApp.student', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/student', {
templateUrl: 'student/student.html',
css: 'student/assets/student.css',
controller: 'studentCtrl',
demand: 'admin'
});
}])
.controller('studentCtrl', ['$scope', 'baseDataUrl', '$http', function($scope, baseDataUrl, $http) {
$scope.update = function() {
$http.get(baseDataUrl + '/student/list').then(function(res) {
$scope.students = res.data;
});
};
$scope.orderProp = "name";
$scope.update();
}]);
how can i do this as there is no way to inject the controller to the config as I know
You could write something like...
angular.module('myApp.student', ['ngRoute'])
.config('routeConfig', function($routeProvider) {
$routeProvider.when('/student', {
templateUrl: 'student/student.html',
css: 'student/assets/student.css',
controller: 'studentCtrl',
demand: 'admin',
resolve: { students : function ($http, baseDataUrl) {
return $http.get(baseDataUrl + '/student/list').then(function (res) {
return res.data;
});
}
}
});
})
.controller('studentCtrl', ['$scope', function($scope, students) {
$scope.students = students;
$scope.orderProp = "name";
}]);
Note that baseDataUrl must either be a constant, or a provider that calls a function to get the required data (in which case, it should be something like baseDataUrl.getUrl()).
With this, it is ensured that every time the /student route is accessed, the scope variable $scope.students contains updated data.

inject service[declared in separate file] in app.config or use it in a controller

I am trying to use the code from here to show routes only when a promise is TRUE
I am following this for my directory structure
app
- Orders
-orders.html
-OrderController.js
-OrderService.js
Main-Config [app.js]
var myApp = angular.module('myApp', ['ngRoute','ngAnimate','ui.bootstrap','myApp.OrderController']);
myApp.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$routeProvider
.when('/orders', {
templateUrl: 'orders/orders.html',
controller: 'OrderController',
resolve:{
customerExpenses: function(OrderService){
return OrderService.getOrders($route.current.params.customerName);
}
}
})
})
OrderService.js
angular.module('myApp').factory('OrderService', ['$http', function($http) {
var sdo = {
getNames: function() {
var promise = $http({
method: 'GET',
url: ''
});
promise.success(function(data, status, headers, conf) {
return data;
});
return promise;
}
}
return sdo;
}]);
I have tried the Accepted answer from here, and one of the suggestion from another SO article
angular.module('myApp')
.service('FooService', function(){
//...etc
})
.config(function(FooServiceProvider){
//...etc
});
As I have my service in a different file, I am trying to determine if I can use it in app.js file without using provider or is that the only way to use service in app.config?
UPDATE 1:
If i want to use the service in a controller
angular.module('myApp.OrderController',[]).controller('OrderController', function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
});
I get OrderService not available
Have tried this:
angular.module('myApp.OrderController',[]).controller('OrderController', ['$scope','OrderService',function ($scope) {
$scope.displayed=[];
$scope.displayed.push(OrderService.getNames());
}]);
followed example :
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
but can not use my service. my controller and service are in different files
I added this question here as I feel they are somewaht related.
You have not injected your service OrderService, change your code in very first line
var myApp = angular.module('myApp', ['ngRoute','ngAnimate', ....'OrderService'])
myApp.config(function($routeProvider, $locationProvider, OrderService){
....
})
Rest of the code looks good

Angular Js Errors are not understandable

I am unable to understand the errors of Angular JS. I am trying to build a factory but it keeps on giving me the following error in firefox console.
Error: [ng:areq] http://errors.angularjs.org/1.2.9/ng/areq?p0=hospitalController&p1=not%20a%20function%2C%20got%20undefined
My Code is
index
<div class="main ng-scope" ng-view="">
partial
<button data-ng-click="ShowStaff()">show</button>
app.js
var myApp = angular.module('myApp', [
'ngRoute',
'artistControllers'
]);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'partials/list.html',
controller: 'ListController'
}).
when('/hospital', {
templateUrl: 'partials/hospital.html',
controller: 'hospitalController'
}).
when('/docter', {
templateUrl: 'partials/docters.html',
controller: 'docterController'
}).
when('/details/:itemId', {
templateUrl: 'partials/details.html',
controller: 'DetailsController'
}).
otherwise({
redirectTo: '/hospital'
});
}]);
controller.js
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.artists = data;
$scope.artistOrder = 'name';
});
// Starting Factory for Doctor and hospital relationship
artistControllers.factory( 'StaffFactory','$http',function(){
var factory = {};
$http.get('js/hospital.json').success(function(data) {
factory.hospitals = data;
//$scope.hospitalOrder = 'name';
});
$http.get('js/docters.json').success(function(data) {
factory.doctors = data;
//$scope.hospitalOrder = 'name';
});
factory.getDocs = function(){
return factory.doctors;
};
factory.getHos= function(){
return factory.hospitals;
};
factory.getStaff = function(){
var result=[];
var endres=[];
angular.forEach(factory.hospitals, function(hospital){
result=[];
angular.forEach(factory.doctors,function(doc){
if(doc.id==hospital.id)
{
result.push(doc);
}
});
endres.push([hospital,result]);
});
return endres;
}
return factory;
});
artistControllers.SimpleController=function($scope,StaffFactory){
$scope.customers=[];
$scope.hospitals=[ ];
$scope.doctors=[];
$scope.staff=[];
init();
function init()
{
$scope.doctors=StaffFactory.getDocs();
$scope.hospitals=StaffFactory.getHos();
}
$scope.ShowStaff = function()
{
$scope.staff=StaffFactory.getStaff();
}
};
// Ending Factory for Doctor and hospital relationship
}]);
In addition to the actual error explained by #dave, if you want eror messages to be more explicit without having to follow a link, you should use angular.js instead of angular.min.js (the minimized one) for your development environment.
If you follow the link in the error, you will see
Argument 'hospitalController' is not a function, got undefined
It sounds like you have in your html somewhere:
ng-controller="hospitalController"
but you haven't created a controller with that name.

Resources