我学习角度的基础知识,我无法理解,为什么ng-repeat不起作用。
文件app.js
(function(){
var app = angular.module('store', [ ]);
app.controller('StoreController', function(){
this.product=gems;
});
var gems = [
{
name: "Dodecahedron",
price: 2.95,
description: '...',
canPurchase: true,
},
{
name: "Pentagonal Gem",
price: 5.95,
description: '...',
canPurchase: false,
}
];
})();
的index.html
<!DOCTYPE html>
<html ng-app="store">
<head>
<link rel="stylesheet" type="text/css" href="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.product.name}}</h1>
<h2> ${{store.product.price}}</h2>
<p>{{store.product.description}}</p>
<button ng-show="store.product.canPurchase"> Add to Cart </button>
</div>
</body>
</html>
想补充一点,如果我尝试查看它不是dinamically(如store.product [0] .description),它会定期工作。
答案 0 :(得分:2)
您在html中使用products
变量。所以用这个替换:
this.products=gems;
答案 1 :(得分:1)
(function(){
var app = angular.module('store', []);
app.controller('StoreController', function ($scope) {
$scope.products = [{
name: "Dodecahedron",
price: 2.95,
description: '...',
canPurchase: true,
}, {
name: "Pentagonal Gem",
price: 5.95,
description: '...',
canPurchase: false,
}];
});
})();
<body ng-controller="StoreController as store">
<h1>APP</h1>
<div ng-repeat="product in products">
<h1>{{product.name}}</h1>
<h2> ${{product.price}}</h2>
<p>{{product.description}}</p>
<button ng-show="product.canPurchase"> Add to Cart </button>
</div>
</body>
答案 2 :(得分:1)
因为你首先分配this.product = gems;然后才定义宝石。另外,您在product
中将产品称为for in
,而不是store.product。工作示例:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
</head>
<body ng-app="plunker">
<div data-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>
</div>
<script>
var app = angular.module('plunker', []);
app.controller('StoreController', ['$scope', function($scope){
this.products=[
{
name: "Dodecahedron",
price: 2.95,
description: '...',
canPurchase: true,
},
{
name: "Pentagonal Gem",
price: 5.95,
description: '...',
canPurchase: false,
}
];
}]);
</script>
</body>
</html>