Robert J. Robert J. - 4 months ago 11
AngularJS Question

angular creating data holder / repository

I am trying to share data between my controllers. I came from C# environment and I was accustomed to creating a class which contains a private member and some methods for retrieving and manipulating / storing data.

Here is a super simple example of what I have in mind

public class MyRepository
{
private List<string> Items { get; set; }

public MyRepository()
{
Items = new List<string>();
}

public List<string> Get()
{
return Items;
}

public string GetById(int Id)
{
return Items[Id];
}

public void AddItem(string sNewItem)
{
Items.Add(sNewItem);
}

public void DeleteItems()
{
Items.Clear();
}

}


Now coming back to Angular, I did some research and found out that in order to be able to share data (to create the above mentioned repository) I have to create something called
Service
. Ok, no problem I followed a guide and came up with something like this:

angular.module("IP-APP", ["ngRoute"])
.factory("Item", function () {
var savedItem = {};

function set(newItem) {
savedItem = newItem;
};

function get() {
return savedItem;
};

return {
set: set,
get: get
};
})


Which I can afterwards inject into my controllers. This works perfectly fine until I try to define my own method such as
GetById
. Suddenly Angular returns the
.GetById is not a function


My question then is - Is it possible to create a repository in a way I have already mentioned (with the ability to define custom functions such as GetById)? If yes, how to do it properly?

Any help in this matter would be more than appreciated.

Answer

Please see a possible solution using the service approach for sharing data across your angular project.

I've simulated setting your data, and return all or a specific item by id. See the code or the JSFiddle

View

<div ng-app="myApp">
 <div ng-controller="testCtrl">
    <b>Get all Service data</b><br/>
    <div ng-repeat="bot in data">
      {{bot.name}}   {{bot.id}}
    </div>
    <br/><br/>
    <b>Get 1 item with id from service</b><br/>
    {{bot.name}} - {{bot.id}}
  </div>
</div>

Controller & Service

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

// Service (singleton)
myApp.service('userService', function() {
    // data
  var savedItems = [];

  function setItem(newItem) {
    if(angular.isUndefined(newItem)) return;
    savedItems[newItem.id] = newItem;
  };

  function getAll() {
    return savedItems;
  };

  function getById(id) {
    if(angular.isUndefined(id)) return;
    return savedItems[id];
  };

  return {
    set: setItem,
    getAll: getAll,
    getById: getById
  };


});

// controller
myApp.controller("testCtrl", function($scope, userService) {
    // set data
  userService.set({'name' : 'bot1', 'id':1});
  userService.set({'name' : 'bot2', 'id':2});
  userService.set({'name' : 'bot3', 'id':3});
  userService.set({'name' : 'bot4', 'id':4});
    // get all
  $scope.data = userService.getAll();
  // get bot1 by id 1
  $scope.bot = userService.getById(1);
})

See Fiddle for demo