我有以下控制器:
'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); } }]);
我想将绑定的ng模型传递ng-model="symbol_wanted"给以下服务,该模型位于我的视图中…
ng-model="symbol_wanted"
'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} }); }]);
如何连接控制器的作用域以传递到服务中?谢谢!
如何在angularjs中将范围从控制器传递到服务?
您不能将$ scope注入服务,没有像Singleton $ scope这样的东西。
我想将绑定的ng模型传递给以下服务,该模型位于我的视图中,即ng-model =“ symbol_wanted”。
您可以通过以下方式调用服务并传递参数:
.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; }]);
因此,我们将这项服务称为“服务”,并得到如下的承诺:
stockData.query(value) // <-- pass value .then(function (result) { $scope.data = result; }, function (result) { alert("Error: No data returned"); });
顺便说一句,我建议您使用$http.get:
$http.get
演示小提琴