Angular JS: Directives

Tech
Read Time - 2 mins

Directives are if not the most relevant component of Angular JS, a very essential one. It affords the ability to basically extend HTML and makes code more readable.

Angular JS Directives are also reusable hence creating a more cleaner, easy to debug and easier to test codebase. Consider the code below:

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

Directives basically tell the browser that a new element has been added.

Restrict signals how a particular element is to be used in the browser Restrictions can be set to

Scope signals that information will be passed into this directive through the attribute. Hence info: ‘=’ tells the directive to scan through the element for an attribute called info. The syntax is identical to calling a class to an html element e.g. <h1 class=”someclass”><h1>. In this case, it will be

<cars info=”bmw”>

Scope:{} means is set to empty

The templateUrl is then used to specify the html file used to display the date. Typical html

<h2 class="make"></h2>
<p class="manufacturer"> </p>
<p class="price"> </p

Assuming the scopes have been defined in the MainController eg.

app.controller('MainController', ['$scope', function($scope) {
  $scope.bmw = {
    icon: 'img/bmw.jpg',
    make: 'BMW',
    Manufacturer: 'BMW Company.',
    price: 20,000
  };

  $scope.audi = {
    icon: 'img/audi.jpg',
    make: 'Audi',
    Manufacturerr: 'Audi Motors',
    price: 30,000
  };

  $scope.volkswagen = {
    icon: 'img/volkswagen.jpg',
    make: 'Volkswagen',
    Manufacturer: 'Volkswagen Motors.',
    price: 40,000
  };
}]);

Then data will be called and displayed in the format as defined in cars.html

Kofi

Kofi

Ghanaian born global citizen

comments powered by Disqus
Victor Asante-Kyei © 2021

With Love by Kofi

rss facebook twitter github youtube mail spotify instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora