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.