I am looking at some sample apps build with Angular. I am looking where the models are created / stored. I've noticed that sometimes the model is stored in a plain javascript file, like this:
customer.js:
function customer(){
this.firstName;
this.lastName;
}
customer.prototype.getFullName = function(){
return this.firstName + ' ' + this.lastName;
}
And what I also see is the use of a factory:
customerFactory.js:
app.factory("customer", function(){
return function(){
this.firstName;
this.lastName;
this.getFullName = function(){
return this.firstName + ' ' + this.lastName;
};
};
});
So my question is, where do you store your model and why? Does the one has more advantages than the other?
I prefer to create a folder called models
and each model gets its own file, defined as a factory. I also use $resource
to define my models, so that I never need to worry about $http
calls (well, almost never).
Why? Because this is the way that Angular apps are built. Doing so allows you to inject them into your controllers, directives, etc. If you prefer to have your models be Angular agnostic, that is fine. It fits with the "Ports and Adapters" architecture. Just expose them as a factory later. Separate your Angular-agnostic code into a separate library, and then just expose them for injection later:
app.factory("Customer", function(){ return Models.Customer; });
app.factory("Order", function(){ return Models.Order; });
Also, notice that I like to name my class objects with capitals... it is a convention I really like to indicate that it is a "class" to be instantiated.
I particularly prefer the second approach, that is, use a factory to create the models.
myApp.factory('Models', [function() {
return {
Customer: (function() {
var cls = function(obj) {
this.firstName = obj && obj.firstName || null;
this.lastName = obj && obj.lastName || null;
}
cls.prototype.getFullName = function() {
return this.firstName + ' ' + this.lastName;
};
return cls;
})(),
Order: (function() {
var cls = function(obj) {
this.id = obj.id || null;
this.amount = obj.amount || null;
}
/* methods */
return cls;
})()
}
}]);
This way, you only has to inject a single dependency in your controllers and it become explicity that the object is a defined model.
myApp.controller('myCtrl', ['$scope', 'Model', function($scope, Model) {
$scope.customer = new Model.Customer({
firstName: "Beterraba"
, lastName: "Abacate"
});
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With