how do i pass scope from controller to service in angularjs?
angularjs, javascript
Solution
how do i pass scope from controller to service in angularjs?
You can't inject $scope into services, there is no such thing as a Singleton $scope.
i want to pass a bound ng-model that sits in my view called ng-model="symbol_wanted" to the following service...
You can call the service and pass parameters this way:
.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;
}]);
So we call this service and get a promise back like this:
stockData.query(value) // <-- pass value
.then(function (result) {
$scope.data = result;
}, function (result) {
alert("Error: No data returned");
});
BTW, I'd suggest you use `$http.get`:
Demo Fiddle
Problem
I have the following 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); } }]); ``` and i want to pass a bound ng-model that sits in my view called `ng-model="symbol_wanted"` to the following service... ``` '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} }); }]); ``` how do i connect the controller's scope to get passed into the service? thanks!