Well so far we have brushed the basics of Angular and its very minimal basics and now I want to create a Sample project to illustrate the rest of the features of Angular to get a better perspective of the framework. Great, I am thinking of creating a Small Application, which will display some cars and its description. This application basically creates a list of cars with titles below and its description on the right hand side with a “More” button. By end of this tutorial you will get a clear understanding of Angular Services, Custom Directives, routing and of course how to use and mix various components of angular in to one application.
PS: I am not going to have any CSS work so the application at the end will just have the functionality covered so feel free to download the application and style it based on your taste.
So now I am going to use the basic Angular set up we have created in the earlier blog. So that just has the Angular bootstrapped and ready for us to start coding.
To start with we need a component which should display the Car thumbnail and below that the title of the Car. So why can’t we create this component as Custom Directive, which we can, reuse through out the application. So I am going to create javascript file called carDetails.js like the below in my directive folder.
carDetails.js
app.directive('carDetails',function(){ return{ template:'<div>My Car</div>' } });
app is nothing but our angular module which we have created in our mainController and assigned to the ng-app in our markup. Here directive takes two parameters, first is the name of the directive and second is the function which will return an object. The returned object will have many attributes which will be used to create the directive, we will be looking at different directive attributes in our later blogs, now we will just get used to a simple directive and usability.
Include the reference of the above created script in your index.html and simply add this html tag inside body of your index.html
<html> <head> <script src="js/lib/angular.min.js"></script> <script src="js/controllers/mainController.js"></script> <script src="js/directives/carDetails.js"></script> </head> <body ng-app="appViewer"> <car-details></car-details> </body> </html>
Just run it.
Now you are seeing the directive contents in your browser and you have created your first directive. Now to see its usage if you keep adding this directive multiple times you will see this String which you have added inside the div of your directive’s template multiple times.
<body ng-app="appViewer"> <car-details></car-details> <car-details></car-details> <car-details></car-details> <car-details></car-details> </body>
If you see the output it will be something like this
So in this tutorial we have seen how to create a simple directive. Next tutorial we will improvise this directive to hold a car thumbnail image and its title.
Leave a Reply