Angular JS: Directives
Read Time - 2 minsDirectives 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.
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
- E (as in this case) matches only element name
- A - matches only element name
- C - matches only class name
- M - matches only comment
Scope signals that information will be passed into this directive through the attribute. Hence info: ‘=’ tells the directive to scan through the
<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