gpt4 book ai didi

javascript - 我如何将范围从 Controller 传递到 angularjs 中的服务?

转载 作者:可可西里 更新时间:2023-11-01 02:19:57 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com