定义模块
var app = angular.module("sachin", ["ng-fusioncharts"]);
//making a service
app.service('team',function(){
var self = {
'runs_aus':0
};
return self;
});
制作工厂
app.factory('taskFactory',function($scope,team){
$scope.myDataSource = {
chart: {
caption: "Runs by opposition",
subCaption: "Runs against each Team",
numberPrefix: "",
theme: "ocean"
},
data:[{
label: "Australia",
value: self.runs_aus
},
{
label: "Pakistan",
value: "7300"
},
{
label: "South Africa",
value: "5900"
},
{
label: "West Indies",
value: "5200"
},
{
label: "England",
value: "3300"
}]
};
return myDataSource;
});
在控制器中注入工厂和服务
app.controller("myCtrl", function($scope,taskFactory,team){
console.log(taskFactory.myDataSource);
//can't access data over here
}
/ *
我想要的只是访问我的Controller中的myDataSource变量
我该怎么做?
先谢谢
答案 0 :(得分:0)
$ scope用于公开要查看的变量,因此您不应在工厂中使用$ scope。要实现您的目标,您可以遵循以下代码示例:
var test = angular.module("test",[]);
test.service("team", function(){
var self = {
'runs_aus':0
};
return self;
});
test.factory('taskFactory',function(team){
var myDataSource = {
chart: {
caption: "Runs by opposition",
subCaption: "Runs against each Team",
numberPrefix: "",
theme: "ocean"
},
data:[{
label: "Australia",
value: team.runs_aus
},
{
label: "Pakistan",
value: "7300"
},
{
label: "South Africa",
value: "5900"
},
{
label: "West Indies",
value: "5200"
},
{
label: "England",
value: "3300"
}]
};
return myDataSource;
});
test.controller("myCtrl", function($scope,taskFactory){
console.log(taskFactory);
//can't access data over here
});
答案 1 :(得分:0)
$ scope是将控制器变量暴露给视图的服务,不应在工厂内使用。
app.service函数使用" new"关键字及其API应该由" this"关键词。即this.myValue = ...,this.myFunction = ...
实际上它有点不同,每次将工厂注入其他函数时都会调用该函数,它应该返回一个包含API的对象。例如:
app.factory('myFactory', function() {
return {
apiVariable: variable,
getVariable: function() { return this.apiVariable }
}
});