简体   繁体   English

Angular.js ng-repeat问题

[英]Angular.js ng-repeat issue

I'm just starting out with Angular and I'm following CodeSchool's videos. 我只是从Angular开始,并且正在关注CodeSchool的视频。 The first part went smoothly, but when trying to replicate the "ng-repeat" part for an array, the html doesn't display the values of the objects, just the directives. 第一部分进展顺利,但是当尝试为数组复制“ ng-repeat”部分时,html不会仅显示指令而显示对象的值。

app.js: 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: 的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>

Again, the code worked when trying with a single gem as a product, but not when I added the second "Pentagonal Gem", even though I followed the video's code word-by-word to check. 同样,该代码在尝试使用单个宝石作为产品时有效,但是,即使我逐个逐个检查视频代码,也无法添加第二个“五角宝石”。 The html site displays exactly what is written in the html document under the h1, h2, and h3 headings. html站点在h1,h2和h3标题下准确显示html文档中的内容。 Help would be greatly appreciated. 帮助将不胜感激。

You need to make gems an array rather than an object . 您需要使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,
}];

You are currently using gem variable as an Object, you need to make it an Array, either by running a loop to push in each Object or just wrapping your inner Object inside square brackets. 您当前正在使用gem变量作为对象,您需要将其设置为数组,方法是运行循环以推入每个对象,或者只是将内部对象包装在方括号内。

(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,
    }];
  });
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM