我的 $scope 中有一个产品列表。我的产品如下所示:
function myController($scope) {
$scope.products = [
{ id:1, name:"hamburger", image:"/img/hamburger.png" },
{ id:2, name:"fries", image:"/img/fries.png" },
{ id:3, name:"hot dog", image:"/img/hotDog.png" }
...
];
}
我有一个名为 food.html 的文件。该文件如下所示:
<div>
<div>{{name}}</div>
<div><img ng-src="{{image}}" /></div>
</div>
我试图通过转发器在index.html中显示我的所有使用food.html呈现的产品的列表。我怎么做?目前,我有这样的东西:
<div ng-controller="myController">
<div>Total Food Items: {{products.length}}</div>
<div ng-repeat="product in products">
</div>
</div>
我不知道如何使用 food.html 渲染每个产品。我该怎么做呢?谢谢!
最佳答案
如果您想使用 food.html 作为模板,请为其创建指令。
angular.module('MyApp').directive('foodDetail', function() {
return {
restrict: 'A',
template: '<div> <div>{{product.name}}</div> <div><img ng-src="{{product.image}}" /></div></div>',
}
});
index.html 应该是
<div ng-controller="myController">
<div>Total Food Items: {{products.length}}</div>
<div ng-repeat="product in products">
<div food-detail></div>
</div>
</div>
关于angularjs - 在 AngularJS 中创建数据模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19451453/