Angular Goodness : Dividing html files into header, footer and body

Clean code is always the best code, hence its best to divide the code in different categories, the most generic we always use is the header, footer and body. So far I had used tag in JSP, but how do we do it if we just have plain html files.
With Angular we can do it it many different ways, lets explore a simple way,
lets say you have a header.html, footer.html and body,
Step1. Create Main.html file, which will include all the parts of the html.
Step2. Add the references to header,footer and include the body . (In case you have multiple bodies then ng:View can be used to replace the htmls based on difft actions)
Below is the code for the same
<html ng-app="testApp"> <!-- remember testApp defines that this is angular app, you can define it at downlevels too -->
<!-- your css files -->
<head>
<link rel="stylesheet" href="css/style.default.css" type="text/css" />
<link rel="stylesheet" href="css/style.navyblue.css" type="text/css" />
<link rel="stylesheet" href="css/responsive-tables.css">
<script src="js/lib/angular/angular.js"></script>
<script src="js/lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script>
facturaApp.controller('ParentViewController', function($scope,$location) {
$scope.supplierEntity = 'suppliers';
$scope.hasHeader = function() {
if($location.path() === "/")
return false;
else
return true;
}
</scirpt>
</head>
<body>
<!-- ParentViewController is the Angular controller where hasHeader() method is written..
Note - all the controllers defined below it will always have access to values in ParentViewController -->
<div ng-controller="ParentViewController">
<!-- ng-show is a special directive which will display the element only if the conditiion is met i.e return value of the method is true..'
<div ng-show="hasHeader()">
<div ng-include="'views/header.html'"></div>
</div>
<ng-view></ng-view> <!-- if this is angular app with multiple views/bodeies -->
<!-- <div ng-include="'views/body.html'"></div> -->
<div ng-include="views/footer.html"></div>
</div>
</body>
</html>
<!-----app.js ----->
<!-- Incase if you are using ngView, you will need the following code to display the right html parts -->
var facturaApp = angular.module('facturaApp', ['ngResource']);
facturaApp.config(function($routeProvider,$locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/index.html'
})
.when('/welcome', {
templateUrl: 'views/welcome.html'
})
.when('/sample1', {
controller:'SampleController',
templateUrl: 'views/sample1.html'
})
.when('/sample2/:id', {
controller:'ViewController',
templateUrl: 'views/sample2.html'
});
})
view rawgistfile1.txt hosted with ❤ by GitHub
Should you have any questions, feel free to comment
Orginally published Nov 2014

Comments

Popular posts from this blog

Apache Airflow Wait Between Tasks

Hibernate Interview Questions

Java Spring Interview Questions