Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Oct 29, 2014

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
You can’t perform that action at this time.