Search code examples
angularjsdatatemplateangularjs-ng-repeat

Creating data templates in AngularJS


I have a list of products in my $scope. My products look like the following:

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" }
    ...
  ];
}

I have a file called food.html. That file looks like this:

<div>
  <div>{{name}}</div>
  <div><img ng-src="{{image}}" /></div>
</div>

I am trying to show a list of all of my products rendered with food.html in index.html via repeater. How do I do that? Currently, I have something like this:

<div ng-controller="myController">
  <div>Total Food Items: {{products.length}}</div>
  <div ng-repeat="product in products">
  </div>
</div>

I'm stuck how to render each product using food.html. How do I do this? Thank you!


Solution

  • If you want to use food.html as an template then create directive for it.

    angular.module('MyApp').directive('foodDetail', function() {
    return {
        restrict: 'A',
        template: '<div> <div>{{product.name}}</div> <div><img ng-src="{{product.image}}" /></div></div>',
    
        }
    });
    

    And index.html should be

    <div ng-controller="myController">
        <div>Total Food Items: {{products.length}}</div>
        <div ng-repeat="product in products">
        <div food-detail></div>
        </div>
    </div>