如何使用Angularjs显示对象属性 [英] How to show object property with Angularjs
问题描述
好.开始了.我正在尝试使用MEAN构建简单的应用.当我用角度 {{object}}
显示对象时,它将在页面上打印该对象,但是当我尝试打印对象属性 {{object.property}}
时,什么也没有发生.
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?
蒙哥
> db.myapp.find().pretty()
{
"_id" : ObjectId("564983745dc4b169cba8c9fc"),
"type" : "balance",
"value" : "111"
}
服务器代码
app.get('/myapp', function (req,res) {
db.myapp.find(function(err,docs){
res.json(docs);
});
});
控制器
$http.get('/myapp').success(function (response) {
$scope.balance = response;
});
HTML
<p>{{balance}}</p>
<p>{{balance.type}}</p>
<p>{{balance.value}}</p>
以下是带有上述HTML的结果.
Result with the above HTML is following.
[{"_id":"564983745dc4b169cba8c9fc","type":"balance","value":"111"}]
推荐答案
正如JSON所示,balance不是对象.它是一个包含单个元素(即对象)的数组.所以你需要
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 }}
打印类型.
如果REST服务应该返回单个对象,则对其进行修复.如果确实应该返回多个元素,则视图应具有一个循环以显示所有元素:
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>
这篇关于如何使用Angularjs显示对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!