2016-06-10 94 views
0

我剛剛開始使用Angular,我正在關注CodeSchool的視頻。第一部分進行得很順利,但是當試圖爲數組複製「ng-repeat」部分時,html不會顯示對象的值,只是指令。Angular.js ng-repeat問題

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> 

再次,單一的寶石作爲產品試圖在代碼的工作,但不是當我添加第二個「Pentago」 nal Gem「,儘管我一直逐字檢查視頻的代碼。 html網站顯示h1,h2和h3標題下的html文檔中的內容。幫助將不勝感激。

+1

您正在將'gems'定義爲一個對象 - 您的意思是定義一個數組嗎? –

+0

如果JavaScript控制檯中沒有錯誤,我會非常驚訝。你應該看到*「Uncaught SyntaxError:意外的標記{」* – Phil

+0

謝謝泰迪,就是這樣。我現在覺得很愚蠢。 – MoSheikh

回答

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

您正在用寶石變量作爲一個對象,你需要一個數組,可以通過運行一個循環中的每個對象推或只是包裹在方括號內的內部對象做出來。

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