Last active
August 29, 2015 14:01
-
-
Save alexpaluzzi/5595e579ed97c6a1a5ef to your computer and use it in GitHub Desktop.
Constructor functions the "Angular way" (slightly opinionated)
This file contains hidden or 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
// 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", "[email protected]"); | |
john.printUser(); // prints "john69" in console | |
//or | |
$scope.john = UserService.getUser("john69", "[email protected]"); | |
$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