简而言之,角度服务总是让我困惑,我似乎通过反复试验让他们工作。我想知道为什么在这种情况下数据返回undefined。
应用模块:
var app = angular.module('myApp', ['services']);
服务:
//creating a service module
var appServices = angular.module('services', []);
appServices.factory('Data', function(){
return {message : "I am data"}
});
控制器:
app.controller('firstCtrl',['Data',
function($scope, Data){
//get data from the service
$scope.data = Data;
console.log(Data);
}]);
app.controller('secondCtrl',['Data',
function($scope, Data){
//get data from the service
$scope.data = Data;
}]);
如果我控制日志数据,我只是得到“未定义”。 我只是想做一个简单的例子来返回对象{message:“我是数据”} 这样
$ scope.data =数据;
然后在视图中
data.message =“我是数据”
真的很感谢解释为什么这不起作用。感谢
答案 0 :(得分:3)
您没有将$scope
注入控制器。将其更改为:
app.controller('firstCtrl', [
'$scope', // There should be an element of this array for each parameter
'Data',
function($scope, Data){
//get data from the service
$scope.data = Data;
console.log(Data);
}
]);
由于您只注入Data
服务,它会映射到控制器函数的$scope
参数,并且没有任何内容映射到Data
参数(并且因为一个变量,尚未分配值隐式具有值undefined
,您会看到undefined
)。
答案 1 :(得分:0)
你可以使用上面的答案,但你可以使用
app.controller('firstCtrl', function($scope, Data){
//get data from the service
$scope.data = Data;
console.log(Data);
});
这样可以正常工作,不需要在控制器中传递服务和函数的数组,因为第二个参数只是函数才能正常工作。