2014-02-20 51 views
1

簡單地說,角度服務總是讓我感到困惑,而我似乎通過反覆試驗讓他們工作。我想知道爲什麼在這種情況下數據返回未定義。簡單的角度服務混淆

應用模塊:

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;

然後在視圖

data.message =「我是數據」

會很感激的,爲什麼這是行不通的解釋。謝謝

回答

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)。

+0

謝謝,傻我:D –

0

,你可以使用上面的答案,但你可以使用

app.controller('firstCtrl', function($scope, Data){ 

    //get data from the service 
    $scope.data = Data; 
    console.log(Data); 
}); 

這將正常工作沒有必要通過服務和功能的陣列控制器作爲第二個參數只是功能將正常工作。