我正在使用Angular Dashboard Framework制作窗口小部件,但是我仍然无法将服务中生成的数据值传递给控制器?我想将var new_x的值传递给在showInfo函数中生成的controller-in服务。但是将其添加到控制器时出现以下错误:
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));
});
您正在从$ 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
}
我添加了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(){.....});
和控制器在另一个模块中并识别dependency
angular.module("controllers", ["services"])
.controller("myController", function(){....});