如何将$scope传递给服务
How do I pass $scope to service
我想获取数据来更新我的表达式{{myList}},但似乎我的服务中存在$scope问题,下面的代码似乎不起作用:
app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){
getTopicContent.request();
}]);
app.factory('getTopicContent', ['$http', function($http, $scope){
var query = function() {
return $http({
url: "http://www.corsproxy.com/mydata.me/level1/list.php",
method: "GET"
}).success(function(data, $scope){
$scope.myList= data;
});
}
return {
request : function(){
return query();
}
}
}]);
但是如果我这样做,它将 http://pastebin.com/T7rjKYds 工作,我运行.success
控制器中,而不是在我的服务中。
服务和工厂与范围无关。他们无法通过依赖关系注入来访问$scope
,以确保关注点的正确分离。
您有两种选择,将$scope
传递给您的getTopicContent.request($scope)
方法,如下所示:
app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){
getTopicContent.request($scope);
}]);
app.factory('getTopicContent', ['$http', function($http){
var query = function($scope) {
return $http({
url: "http://www.corsproxy.com/mydata.me/level1/list.php",
method: "GET"
}).success(function(data){
$scope.myList = data;
});
}
return {
request : function($scope){
return query($scope);
}
}
}]);
或者返回 promise 并在控制器中添加 success()
处理程序:
app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){
getTopicContent.request().success(function(data){
$scope.myList = data;
});
}]);
app.factory('getTopicContent', ['$http', function($http){
var query = function() {
return $http({
url: "http://www.corsproxy.com/mydata.me/level1/list.php",
method: "GET"
})
}
return {
request : function(){
return query();
}
}
}]);
相关文章:
- 从服务返回值时$scope控制器的变量是未定义的
- 将服务中的函数绑定到$scope(错误:无法设置undefined的属性'onChange')
- 如何访问ng-init或ng-checked中服务回调函数中声明的$scope变量
- 角度$scope首先设置值而不是服务,然后第二个函数调用一切正常
- 尝试将 $scope.data 传递到 param 对象中,从控制器传递到 Angular 中的服务
- AngularJs:使用服务传递$scope变量
- AngularJS$scope继承服务
- 如何将$scope传递给服务
- 从 AngularJS 中的服务属性更新$scope
- 通过 .scope().call() 从 JS 外部调用 Angular 服务会挂起请求
- AngularJS:如何将服务方法分配给控制器$scope和ng-repeat(it)
- 从AngularJS中的服务获取数据后,如何更新$scope是最好的方法
- 从AngularJS中的$http服务设置$scope值的最佳方式
- 在服务angularjs中的函数中使用$scope
- 从$http将数据从单独的服务文件获取到$scope中
- 将$scope传递给Angularjs中的服务
- AngularJS$scope.foo是用服务设置的,但后来在同一个控制器中未定义
- 在$http服务中使用$scope作为json数据
- 从服务传递错误消息到控制器$scope
- 将变量从控制器传递到服务$scope