Search code examples
javascriptangularjsangularjs-controllerangularjs-factory

AngularJS : Services are not resolved in my controller


Angularjs controller unable to resolve the service data.

var kattaApp = angular.module('kattaApp', []).controller('kattaController', function($scope, dataFactory) {
    var promise = dataFactory.getResult().then(function(data) {
        return data;
        console.log(data);
    });
    promise.then(function(data) {
        $scope.message = data;
        console.log(data.geonames[0].countrycode);
    });
    console.log(" :'( Scope is  not working  " + $scope.message);
});
angular.module('kattaApp').factory('dataFactory', function($http, $q) {
    return {
        getResult: getResult
    };

    function getResult() {
        var deferred = $q.defer();
        $http.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo').success(function(data, status) {
            deferred.resolve(data);
        }).error(function(data) {
            deferred.reject(data);
        });
        return deferred.promise;
    };
});

In the above code I am trying to set the value for $scope.message. When I am calling the service it is returning the data as undefined and after sometime, getting the data and printing in my console.

Please have a look on my Plnkr Link


Solution

  • You are seeing result like

    :'( Scope is  not working  undefined
    

    in browser console because you have kept

    console.log(" :'( Scope is  not working  "+$scope.message);
    

    outside then call back put it inside then call back and you will get $scope.message with right values.

    If you change promise.then to something like this.

    promise.then(function(data){
         $scope.message = data.geonames[0].countrycode;
             console.log(data.geonames[0].countrycode);
             console.log("$scope.message: "+$scope.message);
      });
    

    you will get message like

    $scope.message: MX

    Here is updated plunker link

    Upadate

    remove $scope from {{scope.message}}

    instead use it like

    <h6>{{ message}}</h6>