Contact Manager

ContactManager

by Mandeep Singh

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div ng-app="app" ng-controller="ContactCntrl">
     <div class="container">
       <label>Name</label>
        <input type="text" name="name" ng-model="newcontact.name" /><br>
        <label>Email</label>
        <input type="text" name="email" ng-model="newcontact.email" /><br>
        <label>Phone</label>
        <input type="text" name="phone" ng-model="newcontact.phone" />
        <br/>
        <input type="hidden" ng-model="newcontact.id" />
        <input type="button" value="Save" ng-click="saveContact()" class="btn btn-primary" />
        </div><br>
    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</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="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>

JavaScript

var module = angular.module('app', []);

module.service('ContactService', function () {
    var uid = 1;
    
    var contacts = [{
        id: 0,
        'name': 'Mandeep',
            'email': '[email protected]',
            'phone': '7777777777'
    }];
  
    this.save = function (contact) {
        if (contact.id == null) {
            contact.id = uid++;
            contacts.push(contact);
        } else {
            for (i in contacts) {
                if (contacts[i].id == contact.id) {
                    contacts[i] = contact;
                }
            }
        }

    }

    this.get = function (id) {
        for (i in contacts) {
            if (contacts[i].id == id) {
                return contacts[i];
            }
        }

    }

    this.delete = function (id) {
        for (i in contacts) {
            if (contacts[i].id == id) {
                contacts.splice(i, 1);
            }
        }
    }

    this.list = function () {
        return contacts;
    }
});

module.controller('ContactCntrl', function ($scope, ContactService) {

    $scope.contacts = ContactService.list();

    $scope.saveContact = function () {
        ContactService.save($scope.newcontact);
        $scope.newcontact = {};
    }


    $scope.delete = function (id) {

        ContactService.delete(id);
        if ($scope.newcontact.id == id) $scope.newcontact = {};
    }


    $scope.edit = function (id) {
        $scope.newcontact = angular.copy(ContactService.get(id));
    }
})