作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有以下 Controller :
'use strict';
/* Controllers */
angular.module('stocks.controllers', []).
controller('MyCtrl1', ['$scope', '$http', 'stockData', function MyCtrl1 ($scope, $http, stockData) {
$scope.submit = function() {
$scope.info = stockData.query();
console.dir($scope.info);
}
}]);
我想将位于我 View 中的名为 ng-model="symbol_wanted"
的绑定(bind) ng-model 传递给以下服务...
'use strict';
/* Services */
angular.module('stocks.services', ['ngResource']).factory('stockData', ['$resource',
function($resource){
return $resource('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', {}, {
query: {method:'GET', isArray:false}
});
}]);
我如何连接 Controller 的范围以传递到服务中?谢谢!
最佳答案
how do i pass scope from controller to service in angularjs?
你不能将 $scope 注入(inject)到服务中,没有 Singleton $scope 这样的东西。
i want to pass a bound ng-model that sits in my view called ng-model="symbol_wanted" to the following service...
您可以这样调用服务并传递参数:
.factory('stockData', ['$resource', '$q', function ($resource, $q) {
var factory = {
query: function (value) {
// here you can play with 'value'
var data = $resource('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json', {}, {
query: {
method: 'GET',
isArray: false
}
});
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
所以我们调用这个服务并得到这样的 promise :
stockData.query(value) // <-- pass value
.then(function (result) {
$scope.data = result;
}, function (result) {
alert("Error: No data returned");
});
顺便说一句,我建议你使用$http.get
:
演示 Fiddle
关于javascript - 我如何将范围从 Controller 传递到 angularjs 中的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19747830/
我是一名优秀的程序员,十分优秀!