Ahmed
Ahmed

Reputation: 1776

using factory in the controller return undefined

I am trying to send value from my view to the controller using function inside ng-click , then use that value to pass it to my factory which goint to pull data from rest api link , but the value im sending return nothing without errors, here is my code

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, idService) {
    $scope.getSo = function (id){
        $scope.myIDs = idService.getID(id); 
    };
});
app.factory('idService', function($http,$q) {
    var oGetID = {};
    oGetID.getID = function(id) {
         var deferred = $q.defer();
        $http.get('http://citysdk.dmci.hva.nl/CitySDK/pois/'+id).then(function(response){

             deferred.resolve(response.data);
     });
    return deferred.promise;
    };
    return oGetID;
});

</script>
</head>
<body>
   <div ng-app="myApp" ng-controller="myCtrl">
        <a href="#" ng-click ="getSo('52527290c5cddb0a7cb654ca');">send variable</a>
        {{myIDs.location.address.value}}
   </div>
</body>
</html>

this is the console result of the responseenter image description here

Upvotes: 0

Views: 29

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

Asynchronous call doesn't work the way you are expecting here. Then happens asynchronously and they return return the data based on API server call. You should expect value after a ajax succeed, by putting .then over it. As internally $http method's return promise.

idService.getID(id).then(function(response){
   alert(response);
   $scope.myIDs = response;
})

Upvotes: 1

Related Questions