2015-04-04 39 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