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
Related
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);
});
}
I've looked at similar questions but I can't seem to understand what I am missing. Basically, I have a service that gets data from the server, and I am trying to get that data into a controller through UI-Router's resolve property. However, after following numerous tutorials and documentations, I can't get the controller to find the data, so to speak. Everything comes up as undefined. I am hoping someone can help me understand what is happening. My code is below.
services.js
myServices.factory('SoundCloudService', ['$http', '$log', '$sce', function($http, $log, $sce) {
function getPlayerHtml() {
return $http.get('/get-site-data').then(function(oEmbed) {
return $sce.trustAsHtml(oEmbed.data.player);
});
};
function getSiteAbout() {
return $http.get('/get-site-data').then(function(oEmbed) {
return $sce.trustAsHtml(oEmbed.data.about);
});
}
function getAllTracks() {
return $http.get('/get-all-tracks').then(function(tracks) {
return JSON.parse(tracks.data);
});
};
function getAllPlaylists() {
return $http.get('/get-playlists').then(function(playlists) {
return JSON.parse(playlists.data);
})
};
function getPlaylist(pid) {
return $http.post('/get-playlist', pid, $http.defaults.headers.post).then(function(playlist) {
return playlist.data;
});
};
function getXMostTrendingFrom(x, playlist) {
var i, trending = [];
playlist.sort(function(a, b) { return b.playback_count - a.playback_count} );
for(i=0;i<x;i++) {
trending.push(all_tracks[i]);
}
return trending;
};
return {
getAllTracks: getAllTracks,
getAllPlaylists: getAllPlaylists,
getPlayerHtml: getPlayerHtml,
getSiteAbout: getSiteAbout,
getXMostTrendingFrom: getXMostTrendingFrom,
getPlaylist: getPlaylist,
};
}]);
app.js
myApp.config(['$stateProvider', '$urlRouterProvider', 'ngMetaProvider',
function($stateProvider, $urlRouterProvider, ngMetaProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('main', {
url: '',
template: '<ui-view/>',
abstract:true,
controller: 'MainController',
resolve: {
player: function(SoundCloudService) { return SoundCloudService.getPlayerHtml(); },
about: function(SoundCloudService) { return SoundCloudService.getSiteAbout(); },
}
})
.state('main.home', {
url: '/',
templateUrl: '../static/partials/home.html',
controller: 'IndexController',
})
.state('main.team', {
url: '/team',
templateUrl: '../static/partials/team.html',
controller: 'TeamController',
})
.state('main.contact', {
url: '/contact',
templateUrl: '../static/partials/contact.html',
controller: 'ContactController',
})
.state('main.resources', {
url: '/resources',
templateUrl: '../static/partials/resources.html',
controller: 'ResourcesController',
})
.state('main.listen-to', {
url: '/listen-to',
templateUrl: '../static/partials/listen-to.html',
controller: 'ListenController',
})
.state('main.listen-to.season', {
url: '/listen-to/:season',
templateUrl: '../static/partials/listen-to.season.html',
controller: 'ListenController',
})
.state('main.listen-to.season.episode', {
url: '/listen-to/:season/:episode',
templateUrl: '../static/partials/listen-to.season.episode.html',
controller: 'ListenController',
})
.state('main.read', {
url: '/read',
templateUrl: '../static/partials/read.html',
controller: 'ReadController',
})
.state('main.read.post', {
url: '/read/:post',
templateUrl: '../static/partials/read.post.html',
controller: 'ReadController',
})
}
]);
controller.js
myControllers.controller('MainController', ['$scope', '$log', 'PageTitleService',
function($scope, $log, PageTitleService, player) {
$log.log(player); /* This is always undefined */
}
]);
[UPDATE]
As pointed out by Hadi in the answer below, I placed player in the array, and the controller now looks like this:
skodenControllers.controller('MainController', ['$scope', '$log', '$sce', 'PageTitleService', 'player',
function($scope, $log, $sce, PageTitleService, player) {
$log.log(player);
}
]);
The console DOES show the data, but only after an error as such:
Error: [$injector:unpr]
http://errors.angularjs.org/1.3.2/$injector/unpr?p0=playerProvider%20%3C-%20player
at angular.js:38
at angular.js:3930
at Object.d [as get] (angular.js:4077)
at angular.js:3935
at d (angular.js:4077)
at Object.e [as invoke] (angular.js:4109)
at F.instance (angular.js:8356)
at angular.js:7608
at r (angular.js:347)
at I (angular.js:7607)
Hopefully someone can lead me in the right direction.
You forgot pass player into array. change to this
myControllers.controller('MainController', ['$scope', '$log',
'PageTitleService','player',
function($scope, $log, PageTitleService, player) {
$log.log(player); /* This is always undefined */
}
]);
As myServices and myControllers are both modules, ensure you add them as dependencies of myApp module.
// init myApp module
angular.module('myApp', ['myServices', 'myControllers']);
Edit
Some leads :
According to the documentation, when using ui-router nested views, child views (state name = main.xxx) must declare the parent state, so you must add parent: "main" or child views won't inherit resolved properties of main state controller
As siteDate is loaded asynchronously in SoundCloudService (services.js:23), you cannot be sure it will be available in your controllers which are loaded at the same time.
Instead, add a getSiteDate() method to SoundCloudService which returns a promise. siteData is then cached and immediately return by the promise.
For example :
/**
* #name getSiteData
* #description Scrap site data
* #returns {promise} a promise
*/
function getSiteData() {
var deferred = $q.defer();
if(siteData) {
deferred.resolve(siteData);
}
else {
$http.get('/get-site-data').then(function(response) {
siteData = response.data;
deferred.resolve(siteData);
}, function(err) {
deferred.reject(err.message);
});
}
return deferred.promise;
}
Why trying to map SoundCloudService to siteData ? You should simply inject SoundCloudService in controllers that use it :
For example :
skodenControllers.controller('MainController', ['$scope', '$log', '$sce', 'PageTitleService', 'SoundCloudService',
function($scope, $log, $sce, PageTitleService, SoundCloudService) {
// Note: getSiteData() could use a cache inside the service
SoundCloudService.getSiteData().then(function(siteData) {
...
});
}
Right now i am making an AngularJS+UI router install application. But i have a problem, the problem is, that i want to disable access to the views, associated with the install application. I want to do it in resolve in the state config.
But the problem is i need to get the data from a RESTful API, whether the application is installed or not. I tried making the function, but it loaded the state before the $http.get request was finished.
Here was my code for the resolve function:
(function() {
var app = angular.module('states', []);
app.run(['$rootScope', '$http', function($rootScope, $http) {
$rootScope.$on('$stateChangeStart', function() {
$http.get('/api/v1/getSetupStatus').success(function(res) {
$rootScope.setupdb = res.db_setup;
$rootScope.setupuser = res.user_setup;
});
});
}]);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/404");
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
data: function($q, $state, $timeout, $rootScope) {
var setupStatus = $rootScope.setupdb;
var deferred = $q.defer();
$timeout(function() {
if (setupStatus === true) {
$state.go('setup-done');
deferred.reject();
} else {
deferred.resolve();
}
});
return deferred.promise;
}
}
})
.state('user-registration', {
url: "/install/user-registration",
templateUrl: "admin/js/partials/user-registration.html",
controller: "RegisterController"
})
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html"
})
.state('404', {
url: "/404",
templateUrl: "admin/js/partials/404.html"
});
}]);
})();
EDIT:
Here is what my ajax call returns:
Try this way:
$stateProvider.state('db-install', {
url: "/install/db",
templateUrl: 'admin/js/partials/db-install.html',
controller: 'DBController',
resolve: {
setupStatus: function($q, $state, $http) {
return $http.get('/api/v1/getSetupStatus').then(function(res) {
if (res.db_setup === true) {
$state.go('setup-done');
return $q.reject();
}
return res;
});
}
}
})
Then inject setupStatus in controller:
.state('setup-done', {
url: "/install/setup-done",
templateUrl: "admin/js/partials/setup-done.html",
controller: ['$scope', 'setupStatus', function ($scope, setupStatus) {
$scope.setupdb = setupStatus.db_setup;
$scope.setupuser = setupStatus.user_setup;
}]
})
I want to make my views show only after the initial data is fetched and i am trying to accomplish this with a route resolve, but i can't get it to work. What am i doing wrong? Also my angular skills are a bit shabby so i aplogize in advance if my question is dumb.
Application.js :
var Application = angular.module('ReporterApplication', ['ngRoute']);
Application.config(['$routeProvider', '$interpolateProvider',
function($routeProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
$routeProvider
.when('/packing/scan.html', {
templateUrl: 'packing/scan.html',
controller: 'PackingScanController',
resolve: {
initData : Application.PackingScanInit()
}
})
.when('/packing/stats.html', {
templateUrl: 'packing/stats.html',
controller: 'PackingStatisticsController'
})
etc
and here is my Scan.js file :
Application.PackingScanInit = function ($q,$timeout,$http) {
var serverData = "";
$http.get('/packing/scan.action')
.success(function(data){
serverData = data;
})
.error(function(data){
serverData = data;
});
return serverData;
}
Application.controller('PackingScanController', ['initData', '$scope', '$http', function(initData, $scope, $http) {
var packer = this;
// Message log model
packer.messageLog = [{
status : "",
message : null
}];
the files are included in this order.
service are singletons means there are initialized only one but time but if you simply return from service it will be called one time but if you return a function from service it will be called again and again .See Below Sample for working.
var app = angular.module('ajay.singhApp', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
resolve: {
myVar: function (repoService) {
return repoService.getItems().then(function (response) {
return response.data;
});
}
}
})
.when('/view2', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/view1'
});
}]);
app.factory('repoService', function ($http) {
return {
getItems: function () {
return $http.get('TextFile.txt');
}
};
});
Try this:
Application.PackingScanInit = function ($q,$timeout,$http) {
return $http.get('/packing/scan.action')
.success(function(data){
return data;
})
.error(function(data){
return data;
});
}
Also you have to adjust your resolve to this:
resolve: {
initData : Application.PackingScanInit
}
Here is a specific working example:
(function() {
angular.module('app',['ngRoute']);
function TestCtrl($scope, initData) {
$scope.value = initData;
}
angular.module('app').config(function($routeProvider) {
$routeProvider.otherwise({
template: '`<p>Dude {{value}}</p>`',
controller: TestCtrl,
resolve: {
initData: function($http) {
return $http.get('test.json') //change to test-e.json to test error case
.then(function(resp) {
return resp.data.value; //success response
}, function() {
return 'Not Found'; // error response
});
}
}
});
});
})();
http://plnkr.co/edit/SPR3jLshcpafrALr4qZN?p=preview
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.