简体   繁体   中英

how to pass values from service to controller in Angularjs

I am making a widget using Angular Dashboard Framework , but I am stuck at how to pass data values generated in services to controller? I would like to pass values of var new_x to controller- in services it is generated in the function showInfo. But I get the following error when adding it to controller:

TypeError: Cannot read property 'showInfo' of undefined
    at new <anonymous> (piechartCtrl.js:62) *(piechartCtrl.js:62 is data: $scope.chartService.showInfo())* 
    at invoke (angular.js:4523)
    at Object.instantiate (angular.js:4531)
    at angular.js:9197
    at $q.all.then.msg (widget-content.js:115)
    at processQueue (angular.js:14792)
    at angular.js:14808
    at Scope.$get.Scope.$eval (angular.js:16052)
    at Scope.$get.Scope.$digest (angular.js:15870)
    at Scope.$get.Scope.$apply (angular.js:16160)

My code is:

angular.module('adf.widget.charts')
   .service('chartService', function(){
  return {
     getUrl: function init(path) {
        Tabletop.init( { key: path,
                         callback: showInfo,
                         simpleSheet: true } )
     }
  }

function showInfo(data, tabletop) {

  var new_x = data.map(function(el) {

  return {
    "name": el[Object.keys(el)[0]],
    "y": +el[Object.keys(el)[1]]
  };

});
    console.log(JSON.stringify(new_x))

};

})


  .controller('piechartCtrl', function (chartService, $scope) {
     $scope.chartConfig = {
        options: {
            chart: {
                type: 'pie'
            }
        },
        series: [{
            data: $scope.chartService.showInfo()
        }],
        title: {
            text: 'Add Title here'
        },

        loading: false
    }


});

Chart.js just in case it is needed:

'use strict';

angular.module('adf.widget.charts', ['adf.provider', 'highcharts-ng'])
  .config(function(dashboardProvider){
    var widget = {
      templateUrl: '{widgetsPath}/charts/src/view.html',
      reload: true,
      resolve: {
        /* @ngInject */
        urls: function(chartService, config){
          if (config.path){
            return chartService.getUrl(config.path);
          }
        }
      },
      edit: {
        templateUrl: '{widgetsPath}/charts/src/edit.html'
      }
  };

  dashboardProvider
      .widget('piechart', angular.extend({
        title: 'Custom Piechart',
        description: 'Creates custom Piechart with Google Sheets',
        controller: 'piechartCtrl'
        }, widget));
  });

you are calling the service from the $scope, replace that line and it should fix it like this:

  series: [{
            data: chartService.showInfo()
        }],

your controller will look like this:

.controller('piechartCtrl', function (chartService, $scope) {
 $scope.chartConfig = {
    options: {
        chart: {
            type: 'pie'
        }
    },
    series: [{
        data: chartService.showInfo()
    }],
    title: {
        text: 'Add Title here'
    },

    loading: false
}

I have added a workable JSFiddle demo to simplify it for you. below is a description to what is there.

Inside your service, return the required methods to be called from controllers:

angular.module('adf.widget.charts')
   .service('chartService', function($q){

      var chartService = {};

      charService.showInfo = function(){

          var new_x = data.map(function(el) {
            return $q.resolve( {
                name: el[Object.keys(el)[0]],
                y: el[Object.keys(el)[1]]
            });

     }
     ...
     return chartService;

   }

Note: Inside your showInfo(), make sure you return a promise using $q , to do that call $q.resolve and pass your returned data to it.

inside your controller:

.controller('piechartCtrl', function (chartService, $scope) {
   chartService.showInfo()
    .then(function(data){
      //your returned data
    });

}

Also make sure that you do the following:

separate your controller definition from service definition and specify in controller module a dependency to service module, I mean

define the service in a separate module:

angular.module("services", [])
.factory("myService", function(){.....});

and controller in a different module and identify the dependency ?

angular.module("controllers", ["services"])
.controller("myController", function(){....});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM