3

I'm trying to pass a parameter from a controller to service in Angular. Here is the controller:

angular.module('CityCtrl', []).controller('CityController',['$scope', '$http', function($scope,$http,CityService){

  $scope.data = "unknown";

  $http.jsonp('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&callback=JSON_CALLBACK').success(function(data){
    $scope.data=data;
  });
  console.log($scope.name);
  if($scope.name){
   $scope.weather = CityService.get($scope.name);
}

     $scope.update = function (zip) {
        $scope.zip = zip;
        console.log(zip);
        $scope.weather = CityService.get({zip: zip});
        alert("Hello, " + zip);
    }
}]);

and here is the service:

angular.module('CityService', []).factory('City', '$scope'['$http', function($scope,$http) {

    return {
        get : function() {
            return $http.get('/cities/' + zip);
        }
     }       
}]);

When I check the console it is logging the correct value, however, when it tried to run the service it says:

Cannot read property 'get' of undefined

For some reason the zip is not being passed to the service. Any idea where the disconnect is?

0

1 Answer 1

2

You would need to inject City Service, When using explicit dependency annotation, it is all or none rule, you cannot just specify part of your dependencies.

angular.module('CityCtrl', []).controller('CityController',
        ['$scope', '$http', 'City'
 function($scope,  $http,  City){

Also you cannot inject $scope in a factory (It is available for injection only to controllers, for directive you get it as an argument in the linking function) and looks like you do not need as well.

angular.module('CityService', []).factory('City', ['$http', function($http) {

    return {
        get : function(zip) {
            return $http.get('/cities/' + zip);
        }
     }       
}]);
Sign up to request clarification or add additional context in comments.

3 Comments

Now I'm getting "ReferenceError: zip is not defined"
Think again why do you get it? you need to pass zip to the service method right. :) Now i dont know how your api serves the purpose for CityService.get($scope.name) and CityService.get({zip: zip}) which you will have to figure about.
Yeah, I was just about to write that I realized I forgot to do that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.