How to model my data is angular js?

10,107 views
Skip to first unread message

David Babaioff

unread,
Oct 21, 2013, 7:34:45 AM10/21/13
to ang...@googlegroups.com
Hi,
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 backbone. In my mind, it's similar to a class in any other OOP language - create a "class" using Backbone.Model.extend(), and call new on it when you want a new instance of that class..
Is this a factory in angular? Is it an ok "best practice" to have a LOT of factories (one for each type of model), basically mimicking "class" with "factory"?

For example, Let's say I want to create objects to map to REST resources and I have an "member" resource that I get by GET-ing: /members/123. This returns a json object with various fields. Something like:

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

Now, I want some kind of representation in my AngularJS app of this "member" object. This representation is more than just a mapping of the fields - I want to add "helper" functions, for example a function that converts the date_create field into something human-readable.

David Babaioff

unread,
Oct 21, 2013, 7:45:01 AM10/21/13
to ang...@googlegroups.com
The factory represents my model with some "helper" functions (like a model on Backbone) or my factory represents a list of members (like a collection on backbone)?

Makarand Bhatamrekar

unread,
Oct 21, 2013, 2:39:30 PM10/21/13
to ang...@googlegroups.com
In Angular you model is defined by the Controllers, for each REST service you can have a Controller which represents your data.. for more info refer to these excellent videos on http://egghead.io/lessons 

Grant Rettke

unread,
Oct 21, 2013, 8:09:51 PM10/21/13
to ang...@googlegroups.com
We want a re-usable data layer that contains the definitions,
constraints, behavior, GUI validators, and service calls. The goal is
to use the same definitions and services across the entire enterprise.
We haven't found a solution yet, but BreezeJS sure is interesting.
> --
> You received this message because you are subscribed to the Google Groups
> "AngularJS" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to angular+u...@googlegroups.com.
> To post to this group, send email to ang...@googlegroups.com.
> Visit this group at http://groups.google.com/group/angular.
> For more options, visit https://groups.google.com/groups/opt_out.



--
Grant Rettke | ACM, AMA, COG, IEEE
gre...@acm.org | http://www.wisdomandwonder.com/
“Wisdom begins in wonder.” --Socrates
((λ (x) (x x)) (λ (x) (x x)))
“Life has become immeasurably better since I have been forced to stop
taking it seriously.” --Thompson

Richard Bill

unread,
Oct 22, 2013, 9:35:09 AM10/22/13
to ang...@googlegroups.com
Factories are not as easily defined as saying that it is like a class that creates new instances. You can create a factory that acts as a class that creates new instances of a JavaScript object (remember JavaScript is prototypal and does not have classes). Another common use for factories is to use them with the by dependency injecting the $http service into the factory and making calls to an external source such as a RESTful service. This might return an array of JSON values that can be converted to an array of objects. The controller, which is the storehouse of the scope, is where models are defined. So you can inject the factory that makes the service call and assign the returned vales to a model on your scope. For instance, say you have a factory that returns students. You have a factory that returns a JSON string of students. You convert this to JavaScript and call this factory (dependency injected into your controller) on a model called $scope.students. So you could have a model $scope.students = studentService;
This the assigns the returned students to the students model. Then in your view, you can call the students model in various forms such as using the ng-repeat built-in directive.

Will Seitz

unread,
Oct 22, 2013, 10:05:33 AM10/22/13
to ang...@googlegroups.com
So the term factory is a little confusing in Angular. The "factory" method just sets up a singleton. The way it differs from a service is whether it is called directly or with constructor syntax. So in the sense that a factory can create multiple objects the "factories" on angular are not factories since they produce a single object that can be injected. So IMHO you should feel free to create lots of "factories"/"services" because they are a key way to encapsulate functionality/data.

As for adding helper functions to objects created from JSON data. I have tried two approaches. One is to modify the the prototype of the object created by your JSON parsing utility. The other is to create a base constructor that takes in an object and will fill in the object with whatever properties are put into that object so you can just call "new MyObjectWithFunctionality(objectFromJSON)"

   constructor(obj: any) { //Sorry for the TypeScript syntax
   for (var p in obj) {
   this[p] = obj[p];
   }
   }
 
Another way would be simple composition (instead of using prototypal inheritance) and just add a behavior object. You would probably want to pass a reference to the object to the behavior block and capture it in a closure and you could make calls like myObject.behavior.displayDate().

Hope this helps.
-Will


On Monday, October 21, 2013 7:34:45 AM UTC-4, David Babaioff wrote:

mark prades

unread,
Nov 1, 2013, 12:05:07 AM11/1/13
to ang...@googlegroups.com
There is model layer(Backbone like) in Angular. You should stick with Backbone Models/Collections if you use them,. "Models" in controllers are presentation models, or ViewModels,not Business Models. Now depending on your app you might need (or not) a model layer.

satish venkatakrishnan

unread,
Nov 1, 2013, 12:49:12 AM11/1/13
to ang...@googlegroups.com
In our project we like to call model it as ViewModel . We model the entities as what my view needs. In most cases we use the plain Javascript classes for doing so. 

We use Services for calling the API/Webservice and the wire the data to the viewmodel as well the default values will be set . 


On Fri, Nov 1, 2013 at 9:35 AM, mark prades <parais...@gmail.com> wrote:
There is model layer(Backbone like) in Angular. You should stick with Backbone Models/Collections if you use them,. "Models" in controllers are presentation models, or ViewModels,not Business Models. Now depending on your app you might need (or not) a model layer.

--

Daniel Tabuenca

unread,
Nov 1, 2013, 2:25:58 AM11/1/13
to ang...@googlegroups.com
Javascript is an incredibly powerful and expressive language. I find one of the best features of angular is it's insistence on using plain old javascript objects rather than requiring extending special classes or using framework-specific constructs in order to support it's two-way data binding model. This distinguishes angular from other frameworks such as Knockout. This really frees you to model your data however you see fit. Many people use models with just data and put listeners and handlers in the controllers, but there's nothing stopping you from enriching your model with functions and taking a more object-oriented approach. 

Javascript makes it easy to intrduce behavior into any object, for example if you can do this:

function addPersonBehaviors(person){
    person.getFullName = function(){
       return this.firstName + " " +this.lastName;
    };
}

var person = addPersonBehaviors(person);
console.log(person.getFullName());

So you could easily add behavior to your models, and you don't need any special framework to do it. 

You are also free to bind handlers such as ng-click to a function that is defined on your model, for example, it is perfectly fine to do something like:

<ul>
    <li ng-repeat='for person in people'> {{person.getFullName()}} <a href="" ng-click="person.doSomething()">Do Something</a></li>
</ul>


As far as your question about factories, unfortunately the angular team managed to cause quite a lot of confusion with how they chose to name factory/service/provider.These are just way to create SINGLETON services that can be shared and injected. A factory is run only once, and it has nothing to do with creating a factory that can be used to build multiple instances of any object, After running once, the single instance that it created will always be used to inject the same service instance.

You can,however feel free to create services for the purpose of adding behavior to your models. One posibility is creating services that abstract fetching particular models from the server. For example, it's quite common to use a repository pattern in your controller:


peopleRepository.getPersonById(5).then( function(person){
    $scope.model = { myPerson:  person };
});

The people repository could then be the perfect place to add additional behavior to objects returned from the server:


module.factory('peopleRepository', function($http){
      return {
         getPersonById: function(id){
             return $http.get('/rest/api/persons/'+id).then(function(person){
                  person.getFullName = function(){
                     return this.firstName+ ' ' + this.lastName;
                  };
                   return person;
             };
         }
      };
});


To summarize, angular really gets out of your way when it comes to dictating how you should structure your data models.  You are free to use the full power of javascript to create rich domain models (if that's what you want to do). 

patrick....@gmail.com

unread,
Nov 2, 2013, 2:16:03 AM11/2/13
to ang...@googlegroups.com
I'm not a professional developer but am teaching myself Javascript/AngularJS for my own use. I was confused originally by examples I had seen on the Angular site about MVC because I always thought that the idea was separation and that Controllers were for wiring together views and models. But if the model exists inside the controller it seems a bit strange to me.

I think of development as designing your model separate to how you're going to present it (including separate to which framework you're going to use) and then wiring it all together at the end.

I also like POJO as I've been finding them simple and effective without the need to add other frameworks. So I'm currently looking at an approach where I would design my model using objects and behaviour, have a test suite for the model and once it's working nicely and if I'm choosing AngularJS for my MVC, I would build a Factory for data transport to/from the model and storage/server. Then I would wire the model in the controller via a $scope.model property and use function properties on $scope to trigger the appropriate functionality within the model.

I've only just come to this possible approach so I don't know if I'm being completely stupid. A few contrived tests seems to indicate that it will work, but I'm not very experienced with Angular and could be kidding myself. But it seems to be in line with how I think about the separation of Model from Controller/View.
Reply all
Reply to author
Forward
0 new messages