ng-repeat不显示对象属性

时间:2015-12-27 01:29:30

标签: angularjs

我有这个HTML:

<html ng-app="store">
<head>
    <link rel="stylesheet" type="text/css" href="./bootstrap/bootstrap-3.3.6-dist/css/bootstrap.min.css" /> 
    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>

<body ng-controller="StoreController as store">
    <div ng-repeat="product in store.products">

            <h1> {{store.products.name}} </h1>
            <h2> {{store.products.price}} </h2>
            <p> {{store.products.description}} </p>
            <p/>
            <button>Add to Cart </button>       
    </div>
</body>

这个JavaScript(即 app.js ):

(function() {
var app = angular.module('store', [ ]); 
app.controller('StoreController', function() {
    this.products = gems;

});
var gems = [
    {
        name: 'Dodecahedron',
        price: 2.95,
        description: 'Some gems have hidden qualities beyond their luster, beyond their shine... Dodeca is one of those gems.',
        canPurchase: true,
        soldOut: false
    },
    {
        name: 'Pentagonal Gem',
        price: 5.95,
        description: 'You will feel right at home.',
        canPurchase: true,
        soldOut: false
    }
]; })();

当我在浏览器中启动html时,会显示&#34;添加到购物车&#34;两个宝石的按钮,但不显示名称价格说明。 当我将以下行添加到html时,它会正确显示第一个gem的价格:

<h2> {{store.products[0].price}} </h2>

显然,我正确地引用了这些产品。

我不知道为什么属性没有显示。

2 个答案:

答案 0 :(得分:1)

您需要将其称为product

<div ng-repeat="product in store.products">
        <h1> {{product.name}} </h1>
        <h2> {{product.price}} </h2>
        <p> {{product.description}} </p>
        <p/>
        <button>Add to Cart </button>       
</div>

答案 1 :(得分:0)

store.products是一个你无法像它一样无法访问的对象数组。如果您想访问当前产品的属性,您需要执行以下操作,

 <div ng-repeat="product in products">
            <h1> {{product.name}} </h1>
            <h2> {{product.price}} </h2>
            <p> {{product.description}} </p>
            <p/>
            <button>Add to Cart </button>       
  </div>

此外,您的代码无法编译,这是工作Application