xyonme
xyonme

Reputation: 395

using service in Angular JS cannot return the scope value

I just tried to create a service in Angular JS , it succeeded call the function $http.get and return the value. However the value isnot inserted into the scope variable. Question : what is wrong?

 angular.module('starter.controllers', [])
.factory('UserService', function($http) {
var data;   
      return{
          getData: function($http) {
              return  $http.get('http://www.website.com/call12').
                    success(function(response) {
                     /// console.log(JSON.stringify(response));
                      userData=response.data;
                            return userData;

                   }).error(function(data, status, headers, config) {
                     // log error
                    });

          }
    }
 })


 .controller('AppCtrl', function($scope, $ionicModal,    $interval,$http,$rootScope,UserService) {

$scope.formData={};
 $scope.userData={};

$scope.myCtrl= function(UserService,$http,$rootScope) {

  UserService.getData($http).then(function(data,$rootScope) {
$scope.userData = data;

 $scope.fullName =  data.name;  
 $scope.balance =  data.balance;

   }}

  $scope.formData.playerName= $scope.userData.name; // $scope.userData is undefined

 $scope.myCtrl(UserService,$http);
 })

Templates

<form ng-submit="submit_editpw()" ng-controller="AppCtrl">  
<pre>userData : {{userData}}</pre> //retuns data
<pre>name: {{fullName}}</pre> //returns empty
</form>

Upvotes: 1

Views: 544

Answers (2)

Karthik Easwaran
Karthik Easwaran

Reputation: 504

In the service return the promise as response and in the controller using the promise success callback assign the value to the userData

 angular.module('starter.controllers', [])
.factory('UserService', function($http) {
var data;   
      return{
          getData: function() {
                  return $http.get('http://www.website123.com/call12');
          }
    }
 })


 .controller('AppCtrl', function($scope, $ionicModal, interval,$http,$rootScope,UserService) {
      $scope.myCtrl= function(UserService,$http) {
      $scope.userData={};

      UserService.getData().success(function(reponse) {
          $scope.userData=response.data;
      });

}

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You are not using asynchronous getData method right. Since this is a promise object you should use its then method:

UserService.getData().then(function(data) {
    $scope.userData = data;
});

Also make sure getData returns a promise:

getData: function () {
    return $http.get('http://m.sepakbola.cc/index.php/id/user/call12').success(function (response) {
        userData = response.data;
        return userData;
    }).error(function (data, status, headers, config) {
        // log error
    });
}

Upvotes: 2

Related Questions