$scope – AngularJS

$scope is an object that connect View with Controller. It holds the model data that we need to pass to view.

Short Project On Scope with description :

Short Project :

HTML :

<!DOCTYPE html>
<html ng-app xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>$scope</title>
 <script type=”text/javascript” src=”//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js“>
</head>
<body>
<div ng-controller = “ContactController”>
<form>
<label>Name :</label>
<input type=”text” name=”name” ng-model = “newcontact.name” />

<br /><br />

<label>Email :</label>
<input type=”text” name=”email” ng-model = “newcontact.email” />

<br /><br />

<label>Phone :</label>
<input type=”text” name=”phone” ng-model = “newcontact.phone” />

<br /><br />

<input type=”hidden” ng-model=”newcontact.id” />
<input type=”button” value=”Save” ng-click = saveContact()”>
</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>E-Mail</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = “contact in contacts”>
<td>{{contact.name}}</td>
<td>{{contact.email}}</td>
<td>{{contact.phone}}</td>
<td>
<a href=”#” ng-click=”edit(contact.id)”>edit</a> |
<a href=”#” ng-click=”delete(contact.id)”>delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

JavaScript :

<script type=”text/javascript”>
var uId = 0;

function ContactController($scope) {
$scope.newcontact = null;
$scope.contacts = [];

//Save
$scope.saveContact = function () {
if ($scope.newcontact.id == null) {
//if id null then add
uId = uId + 1;
$scope.newcontact.id = uId;
$scope.contacts.push($scope.newcontact);
}
else {
// if id is not null then update this contact by it’s id
for (i in $scope.contacts) {
if ($scope.contacts[i].id == $scope.newcontact.id) {
$scope.contacts[i] = $scope.newcontact;
}
}
}
//clear the add contact form
$scope.newcontact = null;
}

//Edit
$scope.edit = function (id) {
for (var i in $scope.contacts) {
if ($scope.contacts[i].id == id) {
//we use angular.copy() method to create
//copy of original object
$scope.newcontact = angular.copy($scope.contacts[i]);
}
}
}

//Delete
$scope.delete = function (id) {
for (var i in $scope.contacts) {
if ($scope.contacts[i].id == id) {
$scope.contacts.splice(i, 1);
$scope.newcontact = {};
}
}
}
}

</script>

Leave a Reply