Skip to content

Instantly share code, notes, and snippets.

@swashcap
Created October 29, 2014 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swashcap/0c54fecfffe67aa6f566 to your computer and use it in GitHub Desktop.
Save swashcap/0c54fecfffe67aa6f566 to your computer and use it in GitHub Desktop.
Models in Angular
// Define the model
(function (angular) {
'use strict';
var Model = function (data) {
this.id = data.ID;
this.name = this._getName(data);
};
Model.prototype._getTitle = function (data) {
return data.firstName + ' ' + data.lastName;
};
Model.prototype.getFancy = function (data) {
return 'Something fancy...';
};
// Export the model to this sweet app
angular.module('mySweetApp')
.factory('Model', function () {
return Model;
});
}(window.angular));
// Use the model
(function (angular) {
angular.module('mySweetApp')
.controller('AwesomeCtrl', function ($scope, $http, Model) {
$scope.models = [];
// Get some models from the server
$http.get('/api/v1/models', function (data) {
angular.forEach(data.data, function (data) {
// Use the Model to wrap the server's data.
$scope.models.push(new Model(data));
});
});
});
}(window.angular));
@swashcap
Copy link
Author

I’ve been struggling with where to put models in Angular. This is a possible solution, although probably not a very good one. The model’s definition could be encapsulated inside the factory. This way, the $http service could be added and the model could do CRUD operations on its own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment