This is basic question on the angularjs service.
I've created a very simple app which has the following code.
var App = angular.module('testApp', ['testService']);
App.config(['$routeProvider', function($routeProvider)
{
$routeProvider
.when('/', {templateUrl: 'partials/dataDisplay.html', controller: testCtrl})
.otherwise({redirectTo: '/'});
}]);
angular.module('testService', []).
factory('svcTest', function($http){
var myService =
{
getPeopleInfo: function()
{
$http.get('/test/app/data/getData.php').success(function(data) {
console.log("Data : " + data.people);
return data.people;
});
}
};
return myService;
});
function testCtrl($scope, svcTest) {
$scope.people = svcTest.getPeopleInfo();
}
When it does '$http.get', I am actually getting the data (and even the getData.php also returns valid JSON.). However the data never gets updated to the testCtrl. Not sure I am doing some thing very silly, being a newbie to Angularjs.
However if I get rid of the services and add the http.get inside the controller, the data is retrieved and updated to the views.
function testCtrl($scope, $http) {
$http.get('/test/app/data/getData.php').success(function(data) {
$scope.people = data.people;
});
}
What is the fundamental issue with the code that I use with the services?
BTW, my HTML is very simple, which displays these info in a simple table format.
Please rewrite your code to as below,
angular.module('testService', []).
factory('svcTest', function($http){
var myService =
{
getPeopleInfo: function()
{
return $http.get('/test/app/data/getData.php')
}
};
return myService;
});
function testCtrl($scope, svcTest) {
var peoplesPromise = svcTest.getPeopleInfo();
peoplesPromise.success(function(data){
$scope.people = data.people
})
}
The $http
returns a promise object which will have success
and error
callbacks to which we can listen.
Getting the promise inside the controller and attaching to the callbacks, gives us the access to scope of the controller (testCtrl
). Then from inside the callback we are updating the testCtrl
's people
property with the response from the request.