Friday, 22 May 2015

Use of ng-include directive

In Angular JS, we can embed HTML pages within a HTML page using ng-include directives. Please refer this example.

includes.html:-
<html>
<head>
<title>Angular JS Includes</title>
<script src="angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="studentController">
<div ng-include="'main.html'"></div>
<div ng-include="'subjects.html'"></div>
</div>
<script src="app.js"></script>
<script src="controller.js"></script>
</body>
</html>


main.html:-
<table border="0">
<tr><td>Enter first name:</td><td><input type="text" ng-model="student.firstName"></td></tr>
<tr><td>Enter last name: </td><td><input type="text" ng-model="student.lastName"></td></tr>
<tr><td>Name: </td><td>{{student.fullName()}}</td></tr>
<tr><td>Fees: </td><td>{{student.fees}}</td></tr>
</table>


subjects.html:-
<p>Subjects:</p>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>
<tr ng-repeat="subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>


controller.js:-
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Anik",
lastName: "Acharjee",
fees:1500,
subjects:[
{name:'Physics',marks:75},
{name:'Chemistry',marks:70},
{name:'Math',marks:74},
{name:'English',marks:79},
{name:'Computer Science',marks:73}
],
fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});


app.js:-
var mainApp = angular.module("mainApp", []);



Screenshot:-




Explanation:-

By using "ng-include" directive in the includes.html file, I have included two html files in it, i.e., main.html & subjects.html.

No comments:

Post a Comment