Monday, 1 June 2015

Use of ng-include & ng-show

Today, I will share one application where I have used ng-include and ng-show directives of Angular JS.


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">
<form>
            <b>Select The Radio Button</b>
            <label class="radio-inline" for="first">
                <input id="first" type="radio" name="regtype" ng-model="regtype" value="basic">Basic Details
            </label>
            <label class="radio-inline" for="other">
                <input id="other" type="radio" name="regtype" ng-model="regtype" value="subject">Subject Details
            </label>
        </form>
<div ng-show="regtype == 'basic'" ng-include="'main.html'"></div>
<div ng-show="regtype == 'subject'" 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>


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


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;
}
};
});



Screenshots:-








Explanation:-

In the above application, two radio buttons are developed. When I click on, one of the radio button, it will display one page and when I click on other radio button, it will display another page.

Since, in the code, I have added ng-show & ng-include,it will display as per the radio click.

In every radio button, one value is assigned. When that value is triggered, by clicking on the radio button, the webpage which has been included to it, using "ng-include", will be shown on the page.

No comments:

Post a Comment