0

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

1
  • is $scope.datas an array? Commented Apr 4, 2015 at 5:13

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @mohamedrias this solves it. I've been using a ng-repeat directive beforehand and that was the problem. @mohamedrias @user: sorry for wasting you time and thanks for the help
0

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>

2 Comments

Ok thanks for your answer, do you think there could be a bug with my install? It's weird. I'll try to launch it in another project and let you know
@t3__rry see this app.controller('MainCtrl',['$scope','blogFactory'], function($scope,blogFactory){, if I'm using in this way It doesn't provide any output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.