4

Aim :- To display only Single Object data. Do I have to use ng-repeat to get the object ?

I'm relatively new to angular. Is there a better way to do this?

Html View :-

<div ng-controller="dashboardController">
    <div ng-repeat="person in persons">
        <span class="name">{{person.name}}</span>
        <span class="title">{{person.title}}</span>
    </div>
</div>

Controller Code :-

.controller('dashboardController', ['$scope', function(scope){
    scope.persons = [
      {
        name:"George Harrison",
        title:"Goof Off extraordinaire"
      }
    ];
}])

UPDATE FOR MY FELLOW NOOBS, array vs single data set:

scope.persons = [ <-- that creates an array. Cant believe I forgot that.
scope.persons = { <-- that creates a single data set

3 Answers 3

4

scope.persons is an array so you have to use ng-repeat. if you your data is an object, you don't need to use ng-repeat. ex: your controller

    .controller('dashboardController', ['$scope', function(scope){
    scope.person ={
        name:"George Harrison",
        title:"Goof Off extraordinaire"
      }

}]);

so your html:

<div ng-controller="dashboardController">
<div>
    <span class="name">{{person.name}}</span>
    <span class="title">{{person.title}}</span>
</div>

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

Comments

3

This can serve your cause with current Json Structure :

 <div ng-controller="dashboardController">
        <div>
            <span class="name"> {{persons[0].name}} </span>
            <span class="title"> {{persons[0].title}} </span>
        </div>
    </div>

2 Comments

Thank you! This works in Angular 1.5 with components. Only thing I changed was the use of ng-controller. It isn't needed in components. I used: {{ $ctrl.persons[0].name }}
@ PPJN You can use either way ... Glad I worked .. Happy Coding !!
1

Normally if you were only getting one item , it would be an object

$scope.beatle = {
     name:"George Harrison",
     title:"Goof Off extraordinaire"
}

then reference that directly in view

{{beatle.name}}

2 Comments

Thank you. So I understand what controllers do. But you are suggesting I do not need a controller. Could you please explain why you would or would not use a controller in this case? If you were going to edit the data in place, would that be a reason you would need a controller?
Yes you need controller. The view is always dependent on the data models in the controller. I'm just saying that when you are expecting only one item it would usually be an object not array

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.