在 Angular 中将参数从控制器传递到服务
Pass parameter from controller to service in Angular
我正在尝试将参数从控制器传递到 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
服务,使用显式依赖注解时,是all或none规则,不能只指定部分你的依赖。
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);
}
}
}]);
我正在尝试将参数从控制器传递到 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
服务,使用显式依赖注解时,是all或none规则,不能只指定部分你的依赖。
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);
}
}
}]);