AngularJS Factory – Basic Example


I do a lot of quick prototyping and I found AngularJS to be the perfect tool for doing just that. The MVVM approach is seamless and smooth. Data storage won’t be an issue since you can use the factory or service static nature to create a session objects and manipulate it using some data collection javascript libraries available.

I primarily use it as a stateless data storage (for prototypes).

angular.module('wall.datafactory', [])

.factory('wall', function() {
    
    var wallitems = [
        {item:[{id:0,type:'review',comments:[],likes:[],meta:[]}]},
        {item:[{id:1,type:'review',comments:[],likes:[],meta:[]}]},
        {item:[{id:2,type:'review',comments:[],likes:[],meta:[]}]},
    ];

    return {
        allWallItems: function(user) {
          return wallitems;
        },
        remove: function(chat) {
          chats.splice(chats.indexOf(chat), 1);
        },
        get: function(chatId) {
          for (var i = 0; i < chats.length; i++) {
            if (chats[i].id === parseInt(chatId)) {
              return chats[i];
            }
          }
          return null;
        }
    };
});

This is one basic approach on how you can use a factory. Create a simple collection array and off you go. Bind that to your controller and you can just use them on the app.

Happy Coding!