Kaimaan
Kaimaan

Reputation: 11

How to show object property with Angularjs

OK. Here we go. I'm trying to build simple app with MEAN. And when I show my object with angular {{object}} it prints the object on my page but when I try to print object property {{object.property}} nothing happens.

Below is the relevant part of the code. How do you print property of the object?

Mongo

> db.myapp.find().pretty()
{
    "_id" : ObjectId("564983745dc4b169cba8c9fc"),
    "type" : "balance",
    "value" : "111"
}

Server code

app.get('/myapp', function (req,res) {
    db.myapp.find(function(err,docs){
        res.json(docs);
    });
});

Controller

$http.get('/myapp').success(function (response) {
        $scope.balance = response;
        });

HTML

<p>{{balance}}</p>
<p>{{balance.type}}</p>
<p>{{balance.value}}</p>

Result with the above HTML is following.

[{"_id":"564983745dc4b169cba8c9fc","type":"balance","value":"111"}]

Upvotes: 0

Views: 9253

Answers (3)

Mukesh Lokare
Mukesh Lokare

Reputation: 2189

HTML

<section class="content row" ng-repeat="item in data">
    Name: {{item.name}} <br/>
    BaseValue: <input type="text" ng-init="item.oldBaseValue = item.baseValue" ng-model="item.baseValue" ng-change="baseValueChange(item.oldBaseValue, item.baseValue); item.oldBaseValue = item.baseValue"/>
</section>

CONTROLLER

$scope.baseValueChange = function(oldVal, newVal) {
    console.log("base value change", oldVal, newVal);
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691635

As the JSON shows, balance is not an object. It's an array, containing a single element, which is an object. So you would need

{{ balance[0].type }}

to print the type.

If the REST service is supposed to return a single object, then fix it. If it's indeed supposed to return several ones, then the view should have a loop to display all the elements:

<div ng-repeat="item in balance">
    {{ item.type }}
</div>

Upvotes: 1

M4N
M4N

Reputation: 96551

It seems your response object is an array (that's why it's rendered in square brackets).

In that case use $scope.balance = response[0] in your controller or {{balance[0].type}} in the markup.

Upvotes: 0

Related Questions