var module = angular.module('myApp', []); module.service('myService', function () { var uid = 1; var contacts = [{ id: 0, 'name': 'jCombat', 'email': '[email protected]', 'mobile': '123456789' }]; var alertTxt = ""; this.save = function (contact) { if (contact.name != null && !angular.isUndefined(contact.name)) { if (contact.id == null) { contact.id = uid++; contacts.push(contact); this.alertTxt = "Saved Successfully!"; } else { for (var i in contacts) { if (contacts[i].id == contact.id) { contacts[i] = contact; } } this.alertTxt = "Updated Successfully!"; } } else { this.alertTxt = "Sorry, cannot be saved!"; } } this.get = function (id) { for (var i in contacts) { if (contacts[i].id == id) { return contacts[i]; } } } this.delete = function (id) { for (var i in contacts) { if (contacts[i].id == id) { contacts.splice(i, 1); } } this.alertTxt = "Deleted Successfully!"; } this.list = function () { return contacts; } }); module.controller('myController', function ($scope, myService) { $scope.contacts = myService.list(); $scope.saveContact = function () { myService.save($scope.contact); alert(myService.alertTxt); $scope.contact = {}; } $scope.delete = function (id) { myService.delete(id); alert(myService.alertTxt); if ($scope.contact.id == id) $scope.contact = {}; } $scope.edit = function (id) { $scope.contact = angular.copy(myService.get(id)); } })
<div ng-app="myApp" ng-controller="myController"> <h3>AngularJS Service demo - jCombat</h3> <h4>Registration Form</h4> <form> <table> <tr> <td> <label>Name</label> </td> <td> <input type="text" name="name" ng-model="contact.name" /> </td> </tr> <tr> <td> <label>Email</label> </td> <td> <input type="text" name="email" ng-model="contact.email" /> </td> </tr> <tr> <td> <label>Mobile</label> </td> <td> <input type="text" name="mobile" ng-model="contact.mobile" /> </td> </tr> <tr> <td colspan="2"> <input type="button" value="Save" ng-click="saveContact()" /> <input type="hidden" ng-model="contact.id" /> </td> </tr> </table> </form> <br/> <h4>Registered Users</h4> <table> <thead> <tr> <th>Name</th> <th>Email</th> <th>Mobile</th> <th>-</th> </tr> </thead> <tbody> <tr ng-repeat="contact in contacts"> <td>{{ contact.name }}</td> <td>{{ contact.email }}</td> <td>{{ contact.mobile }}</td> <td><a href="javascript:void(0)" ng-click="edit(contact.id)">edit</a> | <a href="javascript:void(0)" ng-click="delete(contact.id)">delete</a> </td> </tr> </tbody> </table> </div>
table, th, td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } h3 { color: #e53b2c; }