I am currently writing a code that is displaying the file from json to a charting JS.
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
viewAll.gauge = data;
});
$scope.value = viewAll.gauge[0].value;
However, I am having a hard time taking out the value from my variable array viewAll.gauge. I'm having an error in:
Error: viewAll.gauge[0] is undefined
#http://localhost:8080/js/directives/cpusagegauge.js:11:2
e#http://localhost:8080/js/angular.min.js:35:343
h/<.instantiate#http://localhost:8080/js/angular.min.js:35:474
ce/this.$get</<#http://localhost:8080/js/angular.min.js:68:140
x/<#http://localhost:8080/js/angular.min.js:54:226
q#http://localhost:8080/js/angular.min.js:7:384
x#http://localhost:8080/js/angular.min.js:54:89
g#http://localhost:8080/js/angular.min.js:48:28
g#http://localhost:8080/js/angular.min.js:48:1
g#http://localhost:8080/js/angular.min.js:48:1
x#http://localhost:8080/js/angular.min.js:55:10
g#http://localhost:8080/js/angular.min.js:48:28
x#http://localhost:8080/js/angular.min.js:55:10
z/<#http://localhost:8080/js/angular.min.js:61:261
l/k.success/<#http://localhost:8080/js/angular.min.js:73:32
Re/e/m.promise.then/L#http://localhost:8080/js/angular.min.js:99:147
Re/e/m.promise.then/L#http://localhost:8080/js/angular.min.js:99:147
Re/f/<.then/<#http://localhost:8080/js/angular.min.js:100:321
me/this.$get</g.prototype.$eval#http://localhost:8080/js/angular.min.js:111:1
me/this.$get</g.prototype.$digest#http://localhost:8080/js/angular.min.js:108:458
me/this.$get</g.prototype.$apply#http://localhost:8080/js/angular.min.js:112:323
g#http://localhost:8080/js/angular.min.js:73:285
x#http://localhost:8080/js/angular.min.js:77:322
Ne/</y.onreadystatechange#http://localhost:8080/js/angular.min.js:78:358
http://localhost:8080/js/angular.min.js
Line 93
BTW, my JSON file is pretty small.
[{
"value": "80"
}]
The problem is that the callback of $http.get() is called asynchronously. In your case viewAll.gauge = data;is called after $scope.value = viewAll.gauge[0].value;
The following should work:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.value = data.gauge[0].value;
});
})
Additionally if you want to update scope variables in async callbacks you have to wrap it in $scope.$apply(function() { //your code goes here });. Here is the full example:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.apply(function() {
$scope.value = data.gauge[0].value;
});
});
})
Related
OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:
app.js:
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = [];
function dataService() {
console.log("I am the dataService and I am loaded");
var foo = 1;
function getData () {
return 2;
}
}
})();
I see this on-screen: I am Angular and I am working. so Angular is loading.
I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.
But then the console.log is:
undefined (line 8)
TypeError: dataService.getData is not a function (line 9)
What am I missing?
The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:
function dataService() {
var dataService = this; //get a reference to the service
//attach your functions and variables to the service reference
dataService.foo = 1;
dataService.getData = function() {
return 2;
};
}
An Angular service is very simply an object class. It is also a singleton, meaning it's instantiated only once per run of your app. When the service is instantiated it is very much akin to calling the new operator on your dataService "class":
var $dataService = new dataService();
So, when you inject dataService into your controller, you are actually getting an instance, $dataService, of your dataService "class".
See this blog entry for further reading: https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.sneoo52nk
You are missing the 2nd parameter $http in the function. The named parameters and the actual parameters in function need to be the same, same order and same number. What happened before is that dataService was being assigned an $http instance and the actual dataService was not injected at all because there was no 3rd parameter to inject it into.
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, $http, dataService) {
// ----was missing-----^
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
We have missed the second param '$http' in function. Just add the '$http' param, it should work fine
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope,$http, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
This is how I've been taught to set up services:
function dataService() {
var dataService = {};
var _foo = 1;
var _getData = function () { return 2; }
dataService.foo = _foo;
dataService.getData = _getData;
return dataService;
}
I believe this facilitates public/private methods/vars.
For reference, this is the full code accessing my service:
app.js:
var gridApp = angular.module('gridApp', []);
// create the controller and inject Angular's $scope
gridApp.controller('mainController', ['$scope', 'dataService', function($scope, dataService) {
// create a message to display in our view
$scope.message = 'Angular is working';
var init = function(){
getPackageData();
};
var getPackageData = function (){
return dataService.getData().then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
}
);
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = ['$http'];
function dataService($http) {
var dataService = {};
var _getData = function () {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
return response;
});
}
dataService.getData = _getData;
return dataService;
}
})();
I've spent a few hours on this and I just can't get the array data to display on the page. I'm not getting any errors.
(function() {
var app = angular.module('myApp', []);
app.controller('AppController', ['$http', function($http){
this.files = [];
$http.get('angular-data.json').success(function(data){
this.files = data;
});
}]);
})();
And inside my angular-data.json file:
[{"name": "myfile.doc","ext": "doc","size": "168KB","modified": "5 mins"}]
Someone please help :-(
Convert your .success to .then
Then convert this
this.files = data;
to this
this.files = data.data;
Try this
this.files = data[0];
In angular-data.json file it have object in array
I think the this in success callback is not getting its context.
Try binding it in $scope or if you are using vm, just like
for $scope
(function() {
var app = angular.module('myApp', []);
app.controller('AppController', ['$http', '$scope', function($http, $scope){
$scope.files = [];
$http.get('angular-data.json').success(function(data){
$scope.files = data;
});
}]);
})();
For vm
(function() {
var app = angular.module('myApp', []);
app.controller('AppController', ['$http', function($http){
var vm = this;
vm.files = [];
$http.get('angular-data.json').success(function(data){
vm.files = data;
});
}]);
})();
In my application, I have a service creating a new structure with two json files. So, I use $q.all to use them in a same time.
angular.module('myApp', []).factory('myService', ['$http', '$q', function ($http, $q) {
var myStructure = function () {
var firstJson = $http.get('datas/firstJson.json');
var secondJson = $http.get('datas/secondJson.json');
return $q.all([firstJson, secondJson]).then(function (values) {
var myMap = new Map();
/*
treatment on myMap
*/
return myMap.values();
});
}
return myStructure();
}]);
So, I use this service in myController by using myService.then
var myApp = angular.module('myApp');
myApp.controller('myApp', ['$scope', 'myService', function ($scope, myService) {
myService.myStructure.then(function(value){
$scope.myStructure = value;
});}]);
Finally, when I use {{myStructure}} in my HTML page, after instantiate myApp with ng-controller, the page display {} (an empty object).
Thank you in advance for your help.
Move the myMap logic inside resolve callback in the controller
Service:
angular.module('myApp', []).factory('myService', ['$http', '$q', function ($http, $q) {
var myStructure = function () {
var firstJson = $http.get('datas/firstJson.json');
var secondJson = $http.get('datas/secondJson.json');
return $q.all([firstJson, secondJson]);
}
return myStructure();
}]);
Controller:
var myApp = angular.module('myApp');
myApp.controller('myApp', ['$scope', 'myService', function ($scope, myService) {
myService.myStructure.then(function(values){
var myMap = new Map();
/*
treatment on myMap
*/
$scope.myStructure = myMap.values();
});
}]);
I'm very new to AngularJS, how can I pass input scope from first controller to the second controller for the data $scope.requestURL
I've search about the service method but I have no idea how to apply it.
.controller('ZipController', ['$scope', function($scope) {
$scope.zipCode = '10028';
$scope.setURL = function() {
$scope.requestURL = 'http://congress.api.sunlightfoundation.com/legislators/locate?zip=' + $scope.zipCode + '&apikey=xxxxx';
};
}])
.controller('ListController', ['$scope', '$http',
function($scope, $http) {
$http.get($scope.requestURL).success(function(data) {
console.log(data.results);
$scope.congress = data.results;
});
}]);
Here is a quick solution: ..you don't have to use the $http core service for your case:
You can also read more about angular's constant service..
(function(angular) {
var app = angular.module('myServiceModule', []);
app.controller('ZipController', function($scope, myService) {
$scope.zipCode = '10028';
myService.setFunc($scope.zipCode);
myService.zipCode = $scope.zipCode;
});
app.controller('ListController', function($scope, myService) {
$scope.requestURL = myService.getFunc();
});
app.factory('myService', function() {
var zipCode;
var setFunc = function(zip) {
zipCode = zip;
};
var getFunc = function() {
return 'http://congress.api.sunlightfoundation.com/legislators/locate?zip=' + zipCode + '&apikey=xxxxx'
};
return {
zipCode: zipCode,
setFunc: setFunc,
getFunc: getFunc
};
});
})(window.angular);
Try setting it to $rootScope.requestURL and access it from the second controller.
MY MAIN CONTROLLER
var MyApp = angular.module('ionicApp', ['ionic', 'MobiNav', 'authFactory']);
CONTROLLER CONSUMING FACTORY
MyApp.controller('AuthUser', ['$scope', 'authFactoryService', function ($scope, authFactoryService) {
$scope.showForm = true;
$scope.UserDataLogin = function () {
var loginData = {};
$scope.registration = {
userName: $scope.Auth.userName,
password: $scope.Auth.password,
confirmPassword: $scope.Auth.password
};
authFactoryService.SaveRegistration(registration);
window.scope = loginData;
};
}
]
);
THIS IS THE FACTORY IN SEPERATE FILE
var AuthService = angular.module('authFactory', []);
AuthService.factory('authFactoryService', [
'$http', '$q', '$scope', function ($http, $q, $scope) {
return {
SaveRegistration: function() {
var urlBase = 'http://localhost:48868/';
$http.post(urlBase + 'api/account/register', registration).then(function(response) {
$scope.savedSuccessfully = true;
$scope.message = "User has been registered successfully, you will be redicted to login page in 2 seconds.";
},
function(response) {
var errors = [];
for (var key in response.data.modelState) {
for (var i = 0; i < response.data.modelState[key].length; i++) {
errors.push(response.data.modelState[key][i]);
}
}
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
}]);
error what i'm getting
Error: [$injector:unpr] http://errors.angularjs.org/1.2.17/$injector/unpr?p0=copeProvider%20%3C-%20%24scope%20%3C-%20authFactoryService
at Error (native)
why it is unable to load authFactoryService service
Finally Figured the dug,
$scope was again injected in Factory
replaced
this
AuthService.factory('authFactoryService', [
'$http', '$q', '$scope', function ($http, $q, $scope) {}]);
to this (just removed the $scope which was again injected in factory for dependency.
AuthService.factory('authFactoryService', [
'$http', '$q', function ($http, $q, $scope) {}]);
var AuthService = angular.module('authFactory', []);
You indlcuded the an empty array in your module. This makes it a
module setter, overwriting an existing module.
to fetch a module you use angular.module('authFactory') <-- note the missing second parameter.
Regards
Sander