我试图将参数从控制器传递给Angular中的服务。这是控制器:
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);
}
}]);
这是服务:
angular.module('CityService', []).factory('City', '$scope'['$http', function($scope,$http) {
return {
get : function() {
return $http.get('/cities/' + zip);
}
}
}]);
当我检查控制台时,它正在记录正确的值,但是,当它尝试运行服务时,它说:
Cannot read property 'get' of undefined
由于某种原因,该zip没有被传递到该服务。知道断开连接在哪里吗?
您将需要注入City
Service,在使用显式依赖项注释时,它是全部或没有规则,不能仅指定部分依赖项。
angular.module('CityCtrl', []).controller('CityController',
['$scope', '$http', 'City'
function($scope, $http, City){
同样,您不能$scope
在工厂中注入(它仅可用于控制器注入,对于指令,您可以将其作为链接函数中的参数获取),并且看起来也不需要。
angular.module('CityService', []).factory('City', ['$http', function($http) {
return {
get : function(zip) {
return $http.get('/cities/' + zip);
}
}
}]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句