Skip to content

Instantly share code, notes, and snippets.

@alexpaluzzi
Last active August 29, 2015 14:01
Show Gist options
  • Save alexpaluzzi/5595e579ed97c6a1a5ef to your computer and use it in GitHub Desktop.
Save alexpaluzzi/5595e579ed97c6a1a5ef to your computer and use it in GitHub Desktop.
Constructor functions the "Angular way" (slightly opinionated)
// Factory is a great place to keep the constructor and instance methods
app.factory('User', function() {
function User(username, email) {
this.username = username;
this.email = email;
}
User.prototype = {
printUser: function() {
console.log(this.username);
},
};
return(User);
});
// Service to act as a layer, great place for computations beyond getters/setters, ajax calls, etc
// DI works great, passing in the User "class"
app.service('UserService', ['User', function(User) {
this.getUser = function(username, email) {
// Create an instance like you would normally (with constructor) -- can skip this layer entirely
// if you want to just inject the User factory directly into the controller/directive
var userObj = new User(username, email);
return userObj;
};
}]);
// Calling it from anywhere in the app
// Pass in the services
app.controller('HomeCtrl', ['$scope', 'UserService', function($scope, UserService) {
var john = UserService.getUser("john69", "john@email.com");
john.printUser(); // prints "john69" in console
//or
$scope.john = UserService.getUser("john69", "john@email.com");
$scope.john.printUser(); // prints "john69" in console
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment