0

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"}]

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

awesome, thanks. Does it come out as array from mongo or where does that happen?
I don't know MongoDB very much, and node even less, but I'd guess that a call to db.myapp.find() would indeed retrieve all the elements of the myapp collection, and thus return an array.
0

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.

2 Comments

awesome, thanks. Does it come out as array from mongo or where does that happen?
@Kaimaan: I don't know mongo, but with a quick search I found: find() returns a collection, while findOne() returns the first matching record. See here: mongodb.github.io/node-mongodb-native/markdown-docs/…
0

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

Comments

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.