Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - how do i pass scope from controller to service in angularjs?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...