Created
October 29, 2014 00:26
-
-
Save swashcap/0c54fecfffe67aa6f566 to your computer and use it in GitHub Desktop.
Models in Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.