In the below code, $scope.contactList
contains a list of contacts with an isActive
flag for each contact.
If we invoke $scope.getInactiveCount
from the controller then it will give a count of inactive contacts.
What if we invoke that function from HTML? Will it execute once when DOM loads or execute every time?
Whenever a new contact is added into the list how will the $scope.getInactiveCount
function trigger?
I want to know the flow of angular functions when they are called from HTML pages.
app.js
angular.module('demo',[]).controller('demoController',function($scope){
$scope.contactList=[{firstName:'John',lastName:'Moody',isActive:'Y'},
{firstName:'Chris',lastName:'George',isActive:'Y'},
{firstName:'Anabella',lastName:'Maze',isActive:'N'},
{firstName:'Joseph',lastName:'Butler',isActive:'Y'},
{firstName:'Roni',lastName:'Ray',isActive:'N'},
{firstName:'Tim',lastName:'Cook',isActive:'Y'},
{firstName:'Angel',lastName:'Christina',isActive:'N'}];
$scope.getInactiveCount=function(){
var count=0;
$scope.contactList.forEach(function(d){
if(d.isActive=='N')
count++;
})
return count;
};
$scope.addContact=function(firstName,lastName){
var contact={firstName:firstName,lastName:lastName,isActive:'N'};
$scope.contactList.push(contact);
}
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Calling Angular function from HTML</title>
<script src="angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div data-ng-app='demo'>
<div data-ng-controller='demoController'>
Inactive contacts count: {{getInactiveCount()}}
<br/>
<div>
<input type=text ng-model="firstname">
<input type=text ng-model="lastname">
<br>
<input type='button' value='Add contact' ng-click='addContact(firstname,lastname)' >
</div>
</div>
</div>
</body>
</html>