Angularjs-service data update -


this basic question on angularjs service.

i've created simple app has 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 '$http.get', getting data (and getdata.php returns valid json.). data never gets updated testctrl. not sure doing thing silly, being newbie angularjs.

however if rid of services , add http.get inside controller, data retrieved , updated views.

function testctrl($scope, $http) {         $http.get('/test/app/data/getdata.php').success(function(data) {                  $scope.people = data.people;         }); } 

what fundamental issue code use services?

btw, html simple, displays these info in simple table format.

please rewrite code 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 promise object have success , error callbacks can listen.

getting promise inside controller , attaching callbacks, gives access scope of controller (testctrl). inside callback updating testctrl 's people property response request.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -