Angular.js ng-repeat问题

时间:2016-06-10 01:31:01

标签: javascript angularjs

我刚刚开始使用Angular,我正在关注CodeSchool的视频。第一部分进展顺利,但在尝试复制数组的“ng-repeat”部分时,html不显示对象的值,只显示指令。

app.js:

(function () {
var app = angular.module('store', []);

app.controller('StoreController', function(){
    this.products = gems;


});

var gems = {
    {
    name: 'Dodecaherdron',
    price: 2.95,
    description: 'This is a Dodecahedron',
    canPurchase: true,
    },
    {
    name: "Pentagonal Gem",
    price: 5.95,
    description: "This is a Pentagonal Gem",
    canPurchase: true,
    }
}
})();

HTML:                                          

<body ng-controller="StoreController as store">
    <div ng-repeat="product in store.products">
        <h1>{{product.name}} </h1>
        <h2>${{product.price}}</h2>
        <p>{{product.description}}</p>
        <button ng-show="product.canPurchase">Add to Cart</button>
    </div>


    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
</body>

同样,代码在尝试使用单个宝石作为产品时起作用,但是当我添加第二个“五角宝石”时,即使我逐字逐句地检查视频的代码。 html站点显示h1,h2和h3标题下html文档中写的内容。非常感谢帮助。

2 个答案:

答案 0 :(得分:1)

您需要gems array rather than an object

var gems = [{
  name: 'Dodecaherdron',
  price: 2.95,
  description: 'This is a Dodecahedron',
  canPurchase: true,
}, {
  name: "Pentagonal Gem",
  price: 5.95,
  description: "This is a Pentagonal Gem",
  canPurchase: true,
}];

答案 1 :(得分:0)

您当前正在使用 gem 变量作为Object,您需要将其设置为Array,方法是运行循环以推入每个Object或仅将内部Object包装在方括号内。

(function () {
  var app = angular.module('store', []);

  app.controller('StoreController', function(){
    this.products = gems;

    var gems = [{
      name: 'Dodecaherdron',
      price: 2.95,
      description: 'This is a Dodecahedron',
      canPurchase: true,
    },
    {
      name: "Pentagonal Gem",
      price: 5.95,
      description: "This is a Pentagonal Gem",
      canPurchase: true,
    }];
  });
})();