AngularJS Service End to End

by Bora Kasmer

HTML

<link rel="stylesheet" href="https://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<div ng-app="app" ng-controller="FriendController">
  <form class="well">
    <label>Name</label>
    <input type="text" name="name" ng-model="newfriend.name" />
    <label>Email</label>
    <input type="text" name="email" ng-model="newfriend.email" />
    <label>Phone</label>
    <input type="text" name="phone" ng-model="newfriend.phone" />
    <br />
    <input type="hidden" ng-model="newfriend.id" />
    <input type="button" value="Save" ng-click="saveFriend()" />
  </form>
  <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="friend in friends">
        <td>{{ friend.name }}</td>
        <td>{{ friend.email }}</td>
        <td>{{ friend.phone }}</td>
        <td>
          <a href="#" ng-click="edit(friend.id)">edit</a> |
          <a href="#" ng-click="delete(friend.id)">delete</a>
        </td>
      </tr>
    </tbody>
  </table>
</div>

JavaScript

/// <reference path="angular.min.js" />
var module = angular.module('app', []);
module.service("FirendServices", function() {
  var uid = 2;

  var friendsList = [{
    id: 0,
    'name': 'Engin',
    'email': 'engin@enginpolat.com',
    'phone': '123-2343-44'
  }, {
    id: 1,
    'name': 'Mehmet',
    'email': 'mehmet@pakcamsil.com',
    'phone': '222-3333-54'
  }, {
    id: 2,
    'name': 'Caglar',
    'email': 'caglar@caglarozenc.com',
    'phone': '234-5421-78'
  }];

  this.save = function(friend) {
    if (friend.id == null) {
       friend.id = ++uid;
      friendsList.push(friend);
    } else {
      for (var i = 0; i < friendsList.length; i++) {
        if (friendsList[i].id == friend.id) {
          friendsList[i] = friend;
        }
      };
    }
  }

  this.get = function(id) {
    var result = null;
    angular.forEach(friendsList, function(frnd) {
      if (frnd.id == id) {
        result = frnd;
      }
    });
    return result;
  }

  //iterate through contacts list and delete 
  //contact if found
  this.delete = function(id) {
    angular.forEach(friendsList, function(frnd) {
      if (frnd.id == id) {
        friendsList.splice(friendsList.indexOf(frnd), 1);
      }
    })
  }
  this.list = function() {
    return friendsList;
  }
});

module.controller('FriendController', function($scope, FirendServices) {

  $scope.friends = FirendServices.list();

  $scope.saveFriend = function() {
    FirendServices.save($scope.newfriend);
    $scope.newfriend = {};
  }


  $scope.delete = function(id) {

    FirendServices.delete(id);
    if ($scope.newfriend.id == id) $scope.newfriend = {};
  }


  $scope.edit = function(id) {
    $scope.newfriend = angular.copy(FirendServices.get(id));
  }
})