Angular Js Errors are not understandable - angularjs

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.

Related

Angular Routing and Binding data from controller

I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}

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.

Ajax data via ngResource does not reflect after ngView update through ngRoute :(

I tried a lot and could not find proper answer which can solve my problem. Hope someone will help me out.
app.controller('MainController', ['$scope', 'MainService', 'CONSTANTS', '$routeParams', '$location',
function($scope, MainService, CONSTANTS, $routeParams, $location) {
$scope.indexAction = function() {
MainService.query({format: 'json'}, function(data){
$scope.data = data;
**This data still there when viewAction get call.**
});
}
$scope.newAction = function($event) {
$scope.isNew = true;
angular.isDefined($event)? $event.preventDefault() : false;
if(angular.isDefined($event)) {
var postData = $('#form').serialize();
MainService.save({format: 'json'}, postData, function(data, responseHeader){
var loc = responseHeader('location');
var r = /\d+/;
var dataId = loc.match(r);
$scope.viewAction(dataId[0]);
});
}
else {
$location.path('new');
}
}
$scope.viewAction = function(ObjOrId) {
var dataId = null;
if(angular.isObject(ObjOrId)) {
dataId = ObjOrId.id;
$scope.data = ObjOrId;
$location.path('view/'+dataId);
}
else {
dataId = ObjOrId;
MainService.get({Id: ObjOrId, format: 'json'}, function(data) {
$scope.data = data;
$location.path('view/'+dataId);
});
}
}
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
});
}
]);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/new', {
templateUrl: 'abc.html',
controller: 'MainController'
}).
when('/view/:Id', {
templateUrl: 'xyz.html',
controller: 'MainController'
}).
otherwise({
templateUrl: 'list.html'
})
$locationProvider.html5Mode({
enabled: false
});
}
])
The data which comes in list.html with the help of indexAction that still exists when view route called and I am calling viewAction and loading data from ajax but that new data does not get updated in the view.
Please help!!
Your location.path looks like $location.path('new') when they should look like $location.path('/new');
Your other one looks like $location.path('view/'+dataId) when it should look like $location.path('/view'+ dataId);
I found the answer, I was using ng-model in form template and that was updating the $scope.data object without submitting the form itself, So i changed input directive ng-model to ng-value and while migrating to view template there i am able to get the data.

AngularJS - Mobile Nav - How to install other Controller

I have Probleme with the Controller. Can you help me with this code? I have the Plugin of the Site: http://jtrussell.github.io/angular-snap.js/ the first module does not work :/
I would like to include this code of "MainCtrl" in the controller:
var roomcatApp = angular.module('roomcatApp', [
'ngRoute',
'roomcatControllers',
'roomcatFilters',
'roomcatServices'
]);
roomcatApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/rooms', {
templateUrl: 'partials/room-list.html',
controller: 'RoomListCtrl'
}).
when('/rooms/:roomId', {
templateUrl: 'partials/room-detail.html',
controller: 'RoomDetailCtrl'
}).
when('/rooms/:roomId/map', {
templateUrl: 'partials/room-list.html',
controller: 'MapCtrl'
}).
otherwise({
redirectTo: '/rooms'
});
}]);
angular.module('roomcatApp', ['snap'])
.controller('MainCtrl', function ($scope) {
$scope.snapOpts = {
disable: 'right'
};
});
or do I add this part here?
var roomcatControllers = angular.module('roomcatControllers', []);
roomcatControllers.controller('RoomListCtrl', ['$scope', 'Room',
function($scope, Room) {
$scope.rooms = Room.query();
$scope.orderProp = 'age';
}]);
roomcatControllers.controller('RoomDetailCtrl', ['$scope', '$routeParams', 'Room',
function($scope, $routeParams, Room) {
$scope.room = Room.get({roomId: $routeParams.roomId}, function(room) {
$scope.mainImageUrl = room.images[0];
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}]);
roomcatControllers.controller('MapCtrl', ['$scope', '$routeParams', 'Room',
function($scope, $routeParams, Room) {
$scope.rooms = Room.query();
$scope.room = Room.get({roomId: $routeParams.roomId}, function(room) {
$scope.mainImageUrl = room.images[0];
});
}]);
It seems, you forgot to include angular-snap.js.
It is specified as a dependency in your roomcatApp module:
angular.module('roomcatApp', ['snap'])
But it is not present in your index.html file. Should be included before your app.js and after angular.js
Also, you should include js/app.js after js/directives, js/controllers, js/filters, js/services.

Resources