t3__rry
t3__rry

Reputation: 2849

AngularJS: can't access object property from factory

I have a beginner issue with my AngularJS very simple code: I'm trying to pass data from a factory to a controller and print the object returned to my view, here's my code:

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

In the controller:

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

When I console.log($scope.datas it logs the object fine. In the view I 'm unable to access the object's properties:

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

Does anyone has any idea? Thanks in advance

Upvotes: 0

Views: 1734

Answers (2)

Reena
Reena

Reputation: 1119

This code works fine I have tested it:

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);
})

For the view:

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

Upvotes: 0

mohamedrias
mohamedrias

Reputation: 18566

You don't have any property called name in $scope.datas

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

You must be printing datas.author.

That's why <p>{{data.name}}</p> doesn't display any data.

As per your factory code, post is an object. But in your view you are using

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

Which is not required. Just datas is enough to get that individual post

Upvotes: 1

Related Questions