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"}]
M4N
  • 94,805
  • 45
  • 217
  • 260
Kaimaan
  • 11
  • 1
  • 5

3 Answers3

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>
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • awesome, thanks. Does it come out as array from mongo or where does that happen? – Kaimaan Nov 16 '15 at 08:12
  • 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. – JB Nizet Nov 16 '15 at 08:25
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.

M4N
  • 94,805
  • 45
  • 217
  • 260
  • awesome, thanks. Does it come out as array from mongo or where does that happen? – Kaimaan Nov 16 '15 at 08:12
  • @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: https://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html – M4N Nov 16 '15 at 08:28
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);
}
Mukesh Lokare
  • 2,159
  • 26
  • 38