How to simulate my data in angular js?

Two questions:

1) I am using angular -js and I am looking for a way to model my data. I have experience with the idea of ​​a model in the spine. Is this a factory in angular? Is it a “best practice” to have many factories (one for each type of model), basically mimicking a “class” using “factory”?

Does the factory represent my model with some "helper" functions (for example, a model on the Backbone), or does my factory represent a list of members (for example, collection on the trunk)?

2) For example, let them say that I want to create objects to map to REST resources, and I have a "member" resource, which I get with GET-ing: / members / 123. This returns a json object with various fields. Sort of:

{id: 123, name: 'angularjs', date_created: 1235845}

Now I want some view in my AngularJS application of this member object. This view is more than just matching fields - I want to add “helper” functions, for example, a function that converts a date_create field to something human-readable.

How to present it? using factory + $ resource

+4
source share
1 answer

Here is a good example of how to use factory in your case.

Factory

angular.module('myApp').factory('Member', function($http) {
  // Member is a class which we can use for retrieving and 
  // updating data on the server
  var Member = function(data) {
    angular.extend(this, data);
  }

  // a static method to retrieve Member by id
  Member.get = function(id) {
    return $http.get('/Member/' + id).
      then(function(response) {
      return new Member(response.data);
    });
  };

  // an instance method to create a new Member
  Member.prototype.create = function() {
    var member= this;
    return $http.post('/Member/', member).then(function(response) {
      book.id = response.data.id;
      return member;
    });
  }

  return Member;
});

Then in the controller you can write something like:

controller

var controller = function(Member) {

  var memeber= new Member();
  memeber.name = 'Fox';
  memeber.create();

  // to retrieve a memeber
  var memeberPromise = Memeber.get(123);
  memeberPromise.then(function(b) {
    memeber = b;
  });
};

I used here id, but you understand the flow

Hope this helps you figure it out.

+2
source

All Articles