我正在使用angular dashboard framework创建一个小部件,但我仍然坚持如何将服务中生成的数据值传递给控制器?我想将 var new_x 的值传递给它在函数showInfo中生成的控制器服务。但是在将其添加到控制器
时出现以下错误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)
我的代码是
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以防万一需要
'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));
});
答案 0 :(得分:1)
您正在从$ scope调用该服务,替换该行,它应该像这样修复它:
series: [{
data: chartService.showInfo()
}],
您的控制器将如下所示:
.controller('piechartCtrl', function (chartService, $scope) {
$scope.chartConfig = {
options: {
chart: {
type: 'pie'
}
},
series: [{
data: chartService.showInfo()
}],
title: {
text: 'Add Title here'
},
loading: false
}
答案 1 :(得分:1)
我添加了一个workable JSFiddle demo来为您简化。下面是对那里的描述。
在您的服务中,返回从控制器调用所需的方法:
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;
}
注意:在showInfo()中,请确保使用$q
返回一个承诺,以执行该调用$q.resolve
并将您返回的数据传递给它。
:
.controller('piechartCtrl', function (chartService, $scope) {
chartService.showInfo()
.then(function(data){
//your returned data
});
}
还要确保执行以下操作:
将控制器定义与服务定义分开,并在控制器模块中指定与服务模块的依赖关系,我的意思是
在单独的模块中定义服务:
angular.module("services", [])
.factory("myService", function(){.....});
和控制器在不同的模块中并识别依赖?
angular.module("controllers", ["services"])
.controller("myController", function(){....});