Skip to Content
Learn
Directives
Directives I

Here’s an AngularJS app for a mobile app store:

  • In the controller MainController.js, there are three objects $scope.move, $scope.shutterbugg, and $scope.gameboard that each contain info about an app, like its title and price.
  • In the view index.html in the .main section, each app is displayed inside a .card div.

But looking at the view, the same code is written over and over again to display each app. This is repetitive and error-prone. Let’s fix this.

Instructions

1.

In the new file js/directives/appInfo.js, type in this code:

app.directive('appInfo', function() { return { restrict: 'E', scope: { info: '=' }, templateUrl: 'js/directives/appInfo.html' }; });
2.

Include this new JavaScript file in index.html in line 48 as a <script> element.

3.

In the new file js/directives/appInfo.html. Type in this HTML to display an app’s info:

<img class="icon" ng-src="{{ info.icon }}"> <h2 class="title">{{ info.title }}</h2> <p class="developer">{{ info.developer }}</p> <p class="price">{{ info.price | currency }}</p>
4.

In index.html, replace the contents of the first .card div with the new <app-info> element:

<div class="card"> <app-info info="move"></app-info> </div>
5.

Do the same for the second and third .card divs. Replace their contents with <app-info info="shutterbugg"></app-info> and <app-info info="gameboard"></app-info>

View the AngularJS app in the browser by typing http://localhost:8000.

Folder Icon

Take this course for free

Already have an account?