Sample Angularjs Application - Kids Alphabets Tutor





4.00/5 (3 votes)
Developed Kids Alphabets Tutor using ng-repeat, ng-bind, ng-hide, setTimeout in AngularJS
Introduction
This code displays the content in an array collection with a certain time delay. The tip helps newbies in AngularJs. The code demonstrates the usage of ng-repeat
, ng-bind
, ng-hide
. The array is stored in $scope.letters
and the setTimeout
in the $scope.testname
function sets some delay before the div
binds the data to itself.
Background
Using AngularJs, we can build the rich client UI. This is one of the mostly used Single page applications in the current web application development.
Using the Code
In the array $scope.letters
, we intialized the alphabets to display.
$scope.letters = ['A-Apple', 'B-Ball', 'C-Cat', 'D-Dog',
'E-Elephant', 'F-Frog', 'G-Girafee', 'H-Horse'];
setTimeout
function will set the delay time using the $scope.$apply()
in it and finally the value is returned by the $scope.testname
to the ng-bind
.
<div ng-bind="testname(letter)"> </div>
$scope.testname = function (letter) {
setTimeout(function () {
$scope.test = letter;
$scope.$apply();
}, time);
time = time + 2000;
return letter;
}
Below is the final piece of code to achieve the task.
<html>
<head>
<title>Angular.js Example</title>
<script src="Scripts/angular.js"></script>
<script>
var nameApp = angular.module('NameApp', []);
nameApp.controller('NameCtrl', function ($scope) {
// I initialized only till alphabet 'H'.. Add more if you are topper in LKG.
$scope.letters = ['A-Apple', 'B-Ball', 'C-Cat',
'D-Dog', 'E-Elephant', 'F-Frog', 'G-Girafee', 'H-Horse'];
var time = 0;
$scope.testname = function (letter) {
setTimeout(function () {
$scope.test = letter;
$scope.$apply();
}, time);
time = time + 2000;
return letter;
}
});
</script>
</head>
<body ng-app="NameApp" ng-controller="NameCtrl">
<center>
<h1>Kids Alphabet Tutor</h1><br />
<div ng-hide="letter" ng-repeat="letter in letters">
<div ng-bind="testname(letter)"> </div>
</div>
<h1>
{{test}}
<img src="Images/{{test}}.PNG"
width="75px" height="75px" />
</h1>
</center>
</body>
</html>
Points of Interest
- Image file Name should be the array element names initialized in the
$scope.letters
. $scope.$apply()
is a must and should be there to worksetTimeout
.
How It Looks
Reference link: http://dotnetselflearning.blogspot.in/2015/06/using-settimeout-function-in-angularjs.html