2015-04-04 37 views
0

我有一個初學者問題,我的AngularJS非常簡單的代碼:我試圖從工廠傳遞數據到控制器並打印返回到我的視圖的對象,這裏是我的代碼:AngularJS:不能從工廠訪問對象屬性

angular.module('app').factory('blogFactory',function(){ 
    return { 
     //EDIT 
     post:{"author":"Bob","name":"smith","content":"some content"}, 
     read: function(){ 
      return this.post; 
     } 
    } 
}); 

在控制器:

angular.module('app').controller('MainCtrl',['$scope','blogFactory'], function($scope, blogFactory){ 
    $scope.datas = blogFactory.read(); 
    console.log($scope.datas);}); 

當我console.log($scope.datas它記錄所述對象細。在視圖中,我無法訪問該對象的屬性:

<section class="overview"> 
    <article ng-repeat="data in datas"> 
     <p>{{data.name}}</p> //Doesn't display anything 
     <p>{{data}}</p>  // Displays the object 
    </article> 
</section> 

有沒有人有任何想法?在此先感謝

+0

爲$ scope.datas數組? – mohamedrias 2015-04-04 05:13:43

回答

1

您沒有任何財產$scope.datas

{"author":"Bob","content":"some content"} 

稱爲name必須在打印datas.author

這就是爲什麼<p>{{data.name}}</p>不顯示任何數據。

根據您的工廠代碼,post是一個對象。但在你看來,你正在使用

<article ng-repeat="data in datas"> 

這不是必需的。只是datas足以讓個別職位

+0

謝謝@mohamedrias解決了這個問題。我一直在使用'ng-repeat'指令,那就是問題所在。 @mohamedrias @user:對不起浪費時間和感謝您的幫助 – 2015-04-04 07:36:43

0

此代碼工作正常我測試:

var app = angular.module('app',[]) 
app.factory('blogFactory',function(){ 
return { 
    post:{"author":"Bob","content":"some content"}, 
    read: function(){ 
     return this.post; 
    } 
} 
}); 

app.controller('MainCtrl', function($scope,blogFactory){ 
    alert(); 
$scope.datas = blogFactory.read(); 
console.log($scope.datas); 
}) 

對於視圖:

<body ng-controller ="MainCtrl"> 
<section class="overview"> 
<article ng-repeat="data in datas" > 
    <p>{{data.name}}</p> 
    <p>{{data}}</p>  
</article> 
</section> 
</body> 
+0

好的,謝謝你的回答,你認爲我的安裝可能會有一個錯誤?有點奇怪。我會嘗試在另一個項目中啓動它,並讓你知道 – 2015-04-04 07:26:37

+0

@ t3__rry看到這個app.controller('MainCtrl',['$ scope','blogFactory'],函數($ scope,blogFactory){, m以這種方式使用它不提供任何輸出。 – Reena 2015-04-04 07:30:55